我想,我正在尝试复制cat
以与平台无关的方式使用 Linux shell 的功能,这样我就可以获取两个文本文件并按以下方式合并它们的内容:
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()
然而,这会产生与之前相同的问题,除了中间有“...”之外。显然,换行符被忽略,但我不知道如何正确管理它。
非常感激任何的帮助。
EDIT:
我尝试了 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()
这为我提供了所需的功能,但我仍然对为什么(看似更优雅的)解决方案失败感到有点困惑。