我想,我正在尝试以一种与平台无关的方式复制 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()
这为我提供了我需要的功能,但我仍然对为什么(看似更优雅的)解决方案失败感到困惑。
最佳答案
您已经以二进制模式打开文件,因此不会进行换行转换。不同的平台使用不同的行尾,如果您在 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
,如果使用的换行约定与第一个文件不匹配,可能会引发异常。
关于python - 使用换行符将内容从一个文件附加到另一个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20607661/