同时逐行读取两个文本文件


问题内容

我有两种不同语言的文本文件,它们逐行对齐。即textfile1中的第一行对应于textfile2中的第一行,依此类推。

有没有一种方法可以同时逐行读取两个文件?

以下是文件外观的示例,假设每个文件的行数约为1,000,000。

textfile1:

This is a the first line in English
This is a the 2nd line in English
This is a the third line in English

textfile2:

C'est la première ligne en Français
C'est la deuxième ligne en Français
C'est la troisième ligne en Français

期望的输出

This is a the first line in English\tC'est la première ligne en Français
This is a the 2nd line in English\tC'est la deuxième ligne en Français
This is a the third line in English\tC'est la troisième ligne en Français

有一个Java版本,可以同时逐行读取两个文本文件-
java
,但是Python不使用bufferedreader逐行读取。那怎么办呢?


问题答案:
from itertools import izip

with open("textfile1") as textfile1, open("textfile2") as textfile2: 
    for x, y in izip(textfile1, textfile2):
        x = x.strip()
        y = y.strip()
        print("{0}\t{1}".format(x, y))

在Python 3中,将其替换itertools.izip为内置的zip