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

70

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

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

以下是文件样例,假设每个文件大约有100万行。

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

文本文件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

这里有一个 Java 版本的同时逐行读取两个文本文件的方法 -Java,但是 Python 没有使用可逐行读取的缓冲区读取器,那么该如何实现呢?


4
这不是Python,但如果你只需要将输出保存到一个新文件中,“paste textfile1 textfile2 > output”也可以实现。 - eumiro
如果您喜欢larsmans的回答,您可能想将其标记为已接受。 - Noctis Skytower
4个回答

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

在Python 2中,用itertools.izip替换内置的zip函数:
    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))

我遇到了这个问题: 文件“MergeANNOVARResults.py”,第10行 with open(refseq) as refseq_fh, open(gencode) as gencode_fh: ^ SyntaxError: 无效的语法 - jmtoung
3
这会将textfile1和textfile2的所有内容加载到内存中吗? - user58925

25
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

4
请注意,在Python 2.x中,zip()会将两个文件的全部内容读入内存。 - Hugh Bothwell
1
最好使用 from itertools import izipizip_longest - Martijn Pieters

6
我们可以使用生成器(`generator`)来更方便地打开文件,并且它能够轻松支持同时迭代多个文件。
filenames = ['textfile1', 'textfile2']

def gen_line(filename):
    with open(filename) as f:
        for line in f:
            yield line.strip()

gens = [gen_line(n) for n in filenames]

for file1_line, file2_line in zip(*gens):
    print("\t".join([file1_line, file2_line]))

注意:

  1. 这是Python 3的代码。对于Python 2,请像其他人一样使用itertools.izip
  2. zip会在迭代最短文件后停止,如果有影响,请使用itertools.zip_longest

4

Python可以逐行读取文件,这甚至是默认行为-您只需要像迭代列表一样迭代文件即可。

关于同时迭代两个可迭代对象,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())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接