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

锡:

我有两个使用两种不同语言的文本文件,它们逐行对齐。即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来逐行读取。那怎么办呢?

弗雷德·富(Fred Foo):
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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章