问题描述
考虑制表符分隔的文件 foo.txt
:
chrY 1208806 1208908 + .
chrY 1212556 1212620 + .
chrY 1465479 1466558 + .
目标是操纵 foo.txt
以获得 result.txt
:
chrY:1208806-1208908
chrY:1212556-1212620
chrY:1465479-1466558
此代码有效:
with open(filename,'r') as f:
for line in f:
l = line.split()[0:3]
result = f'{l[0]}:{l[1]}-{l[2]}'
print(result)
但是如果 foo.txt
是一个无法放入内存的巨大文件,那么将每一行保存在列表 l
中是不可行的。如何将前面提到的代码写入 generator/iter
?
谢谢。
解决方法
我过去需要这样做,以处理大约 50GB 以上的文件。您需要做的只是在处理时写出每一行。
with open('foo.txt','r') as src,open('result.txt','w') as tgt:
for line in src:
l = line.split()[0:3]
result = f'{l[0]}:{l[1]}-{l[2]}\n'
tgt.write(result)
(注意 \n
中包含换行符 result
)
以这种方式处理大文件需要一段时间,但 RAM 使用量几乎没有增加。
我刚刚测试了多次复制的示例,效果很好。