如何混合两个文本文件中的行?

时间:2013-09-06 13:45:52

标签: python python-3.x

我有三个要从命令行读入的文件:要写入的文件,要读取的第一个文件以及要读取的第二个文件。

我想在我的文件中写入第一个文件的第一行,第二个文件的第一行,第一个文件的第二行,第二个文件的第二行等等。

这是我到目前为止所做的:

import sys

writeTo, firstFile, secondFile = sys.argv[1: ]

text_file = open(writeTo, "w")

x = open(firstFile, "r")
y = open(secondFile, "r")

for linex in x:
    for liney in y:
        text_file.write(linex+liney)

1 个答案:

答案 0 :(得分:3)

使用zip

with open(firstFile) as f1, open(secondFile) as f2,\
                                             open(writeTo, 'w') as text_file:
    for line1, line2 in zip(f1, f2):
         text_file.write(line1 + line2)

如果文件包含不等数量的行,请考虑使用itertools.zip_longest