【发布时间】: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()
这为我提供了我需要的功能,但我仍然对(看似更优雅的)解决方案失败的原因感到有点茫然。
【问题讨论】:
-
这不是答案,而是
file1、file2参数与函数体中的file_1、file_2不匹配。 -
你尝试过哪些方法逐行阅读?
-
@falsetru 哎呀,是的,那是我的错。谢谢你抓住它。已更正。
标签: python python-2.7 concatenation fasta shutil