我试图在两个文件之间连接片段特定的行.这样我想从file2中的第2行添加一些东西到file1的第2行.然后从第6行从file2到文件1的第6行,依此类推.有没有办法同时迭代这两个文件来做到这一点?(知道输入文件大约为15GB可能会有所帮助).
这是一个简化的例子:
档案1:
Ignore
This is a
Ignore
Ignore
Ignore
This is also a
Ignore
Ignore
Run Code Online (Sandbox Code Playgroud)
文件2:
Ignore
sentence
Ignore
Ignore
Ignore
sentence
Ignore
Ignore
Run Code Online (Sandbox Code Playgroud)
输出文件:
Ignore
This is a sentence
Ignore
Ignore
Ignore
This is also a sentence
Ignore
Ignore
Run Code Online (Sandbox Code Playgroud)
Tri*_*ych 13
Python3:
with open('bigfile_1') as bf1:
with open('bigfile_2') as bf2:
for line1, line2 in zip(bf1, bf2):
process(line1, line2)
Run Code Online (Sandbox Code Playgroud)
重要的是,bf1和bf2不会立即读取整个文件.它们是知道如何一次生成一行的迭代器.
zip() 与迭代器一起工作正常,并且会生成一个交互器本身,在这种情况下,您可以处理成对的行.
使用with确保文件将在之后关闭.
Python 2.x
import itertools
with open('bigfile_1') as bf1:
with open('bigfile_2') as bf2:
for line1, line2 in itertools.izip(bf1, bf2):
process(line1, line2)
Run Code Online (Sandbox Code Playgroud)
Python 2.x不能以相同的方式使用zip - 它会产生一个列表而不是一个可迭代的,用这些15GB文件占用你的所有系统内存.我们需要使用特殊的可迭代版本的zip.