同时迭代两个文件的行

The*_*man 3 python python-2.x

我试图在两个文件之间连接片段特定的行.这样我想从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.

  • @Triptych你应该结合前两行:`open('bigfile_1)为bf1,open('bigfile_2')为bf2:`并使用普通的4空格缩进. (4认同)
  • 请注意,Python 2的`zip`函数返回一个列表,其中包含所有对.这可能会炸毁系统的大文件内存.使用`itertools.izip`获取类似Python 3的`zip`(这是一个生成器)的行为. (3认同)
  • @triptych*python 2*返回列表.你正在展示python 3的文档.请检查API文档的版本. (3认同)
  • 如果它们的长度不同会发生什么? (2认同)