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

2024-05-14 17:58:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个不同语言的文本文件,它们是逐行对齐的。一、 e.textfile1中的第一行对应于textfile2中的第一行,以此类推。

有没有办法同时逐行读取这两个文件?

下面是文件的外观示例,假设每个文件的行数约为1000000。

文本文件1:

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

文本文件2:

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

这个Read two textfile line by line simultaneously -java有一个Java版本,但是Python不使用逐行读取的bufferedreader。那怎么办呢?


Tags: 文件theinenglishislinethisla
3条回答
with open(file1) as f1, open(fil2) as f2:
  for x, y in zip(f1, f2):
     print("{0}\t{1}".format(x.strip(), y.strip()))

输出:

This is a the first line in English C'est la première ligne en Français
This is a the 2nd line in English   C'est la deuxième ligne en Français
This is a the third line in English C'est la troisième ligne en Français
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中,用内置的zip替换itertools.izip

Python允许您逐行读取,甚至是默认的行为—您只需遍历文件,就像遍历列表一样。

wrt/同时遍历两个iterables,itertools.izip是您的朋友:

from itertools import izip
fileA = open("/path/to/file1")
fileB = open("/path/to/file2")
for lineA, lineB in izip(fileA, fileB):
    print "%s\t%s" % (lineA.rstrip(), lineB.rstrip())

相关问题 更多 >

    热门问题