【问题标题】:append contents from one file to another with newline separation使用换行符将内容从一个文件附加到另一个文件
【发布时间】:2014-01-03 15:37:59
【问题描述】:

我想,我正在尝试以与平台无关的方式复制 Linux shell 的 cat 功能,这样我就可以获取两个文本文件并按以下方式合并它们的内容:

file_1 包含:

42 bottles of beer on the wall

file_2 包含:

Beer is clearly the answer

合并文件应包含:

42 bottles of beer on the wall  
Beer is clearly the answer

然而,我读过的大多数技术最终都产生了:

42 bottles of beer on the wallBeer is clearly the answer

另一个问题是我想要处理的实际文件是非常大的文本文件(FASTA 格式的蛋白质序列文件),因此我认为大多数逐行读取的方法效率低下。因此,我一直在尝试使用shutil 找出解决方案,如下所示:

def concatenate_fasta(file1, file2, newfile):
    destination = open(newfile,'wb')
    shutil.copyfileobj(open(file1,'rb'), destination)
    destination.write('\n...\n')
    shutil.copyfileobj(open(file2,'rb'), destination)
    destination.close()

但是,这会产生与前面相同的问题,只是中间有“...”。显然,换行符被忽略了,但我不知道如何正确管理它。

任何帮助将不胜感激。

编辑:

我尝试了 Martijn 的建议,但返回的 line_sep 值是 None,当函数尝试将其写入输出文件时会引发错误。我现在已经通过os.linesep 方法得到了这个工作,该方法被称为不太理想,如下所示:

with open(newfile,'wb') as destination:
    with open(file_1,'rb') as source:
        shutil.copyfileobj(source, destination)
    destination.write(os.linesep*2)
    with open(file_2,'rb') as source:
        shutil.copyfileobj(source, destination)
    destination.close()

这为我提供了我需要的功能,但我仍然对(看似更优雅的)解决方案失败的原因感到有点茫然。

【问题讨论】:

  • 这不是答案,而是file1file2参数与函数体中的file_1file_2不匹配。
  • 你尝试过哪些方法逐行阅读?
  • @falsetru 哎呀,是的,那是我的错。谢谢你抓住它。已更正。

标签: python python-2.7 concatenation fasta shutil


【解决方案1】:

您已以二进制模式打开文件,因此不会进行换行转换。不同的平台使用不同的行尾,如果你在 Windows 上\n不够

最简单的方法是在这里写os.linesep

destination.write(os.linesep + '...' + os.linesep)

但是这可能违反了文件中使用的实际换行约定。

更好的方法是以文本模式打开文本文件,读取一两行,然后检查 file.newlines attribute 以查看该文件的约定:

def concatenate_fasta(file_1, file_2, newfile):
    with open(file_1, 'r') as source:
        next(source, None)  # try and read a line
        line_sep = source.newlines
        if isinstance(line_sep, tuple):
            # mixed newlines, lets just pick the first one
            line_sep = line_sep[0]

    with open(newfile,'wb') as destination
        with open(file_1,'rb') as source:
            shutil.copyfileobj(source, destination)
        destination.write(line_sep + '...' + line_sep)

        with open(file_2,'rb') as source:
            shutil.copyfileobj(source, destination)

您可能还想测试file_2,如果使用的换行约定与第一个文件不匹配,可能会引发异常。

【讨论】:

  • 非常感谢您的详尽回答;我今天会试一试。我最后保存了这部分脚本,认为“将两个文件组合在一起一定很简单”。生活和学习。
  • 不太好用(请参阅更新的 OP);您的其他建议似乎起到了作用,尽管我想知道它是否会像您警告的那样破坏某些东西。
  • @glarue:可能是你需要阅读多行;也许让它成为一个循环读取几行直到设置source.newlines,在你放弃之前有最大的行数。
【解决方案2】:

看来,您的源文件可能没有以换行符结尾。在这种情况下,读取文件的最后一个字符(或更多基于您的平台)以确定其是否为换行符os.linesep 并相应地在输出文件中添加换行符将是有益的。

with open("file1.txt",'rb') as fin1, \
     open("file2.txt",'rb') as fin2,  \
     open("file3.txt",'wb') as fout:
    shutil.copyfileobj(fin1, fout)
    fin1.seek(-len(os.linesep), 2)
    if fin1.read() != os.linesep:
            fout.write(os.linesep)
    shutil.copyfileobj(fin2, fout)

【讨论】:

    【解决方案3】:
    from sys import argv
    from os.path import exists
    
    script, from_file, to_file = argv
    
    print "Copying from %s to %s" % (from_file, to_file)
    
    # we could do these two on one line too, how?
    in_file = open(from_file, 'rb')
    indata = in_file.read()
    
    
    print "Ready, hit RETURN/ENTER to continue, CTRL- C to abort."
    raw_input()
    
    out_file = open(to_file, 'a')
    
    out_file.write(indata)
    print "Alright, all done."
    
    out_file.close()
    in_file.close()
    

    【讨论】:

      猜你喜欢
      • 2020-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-19
      • 2020-02-21
      • 2018-12-06
      • 2019-08-15
      相关资源
      最近更新 更多