使用 Python 3.x 代码合并两个文本文件交替行

Merge two text files alternating lines using Python 3.x code

我需要读取两个文本文件并将它们的交替行写入第三个文件。例如...

文件 1
A1
A2

文件 2
B1
B2

输出文件
A1
B1
A2
B2

在此先感谢您的帮助!

from itertools import zip_longest
with open(filename1) as f1, open(filename2) as f2, open(outfilename, 'w') as of:
    for lines in zip_longest(f1, f2):
        for line in lines:
            if line is not None: print(line, file=of, end='')

编辑:要解决输入文件不以换行符结尾的问题,请将 print 行更改为:

print(line.rstrip(), file=of)

由于文件是可迭代的,因此它们可以 zip 编辑在一起。由于我们希望支持两个输入文件中的行数不匹配的情况,因此我们使用 zip_longest 而不是内置的 zip。这种方法不需要将整个文件加载到内存中,因此它甚至可以用于合并非常大的文件而无需 MemoryError.

import itertools

with open('file1.txt') as src1, open('file2.txt', 'r') as src2, open('output.txt', 'w') as dst:
    for line_from_first, line_from_second in itertools.zip_longest(src1, src2):
        if line_from_first is not None:
            dst.write(line_from_first)
        if line_from_second is not None:
            dst.write(line_from_second)