【问题标题】:Reading two text files line by line simultaneously同时逐行读取两个文本文件
【发布时间】:2012-07-02 22:56:20
【问题描述】:

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

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

下面是文件的样例,假设每个文件的行数约为 1,000,000。

文本文件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。那么如何实现呢?

【问题讨论】:

  • 这不是 Python,但如果您只需要在新文件中输出,paste textfile1 textfile2 > output 也应该可以。
  • 如果您喜欢 larsmans 的回答,您可能希望将其标记为已接受。

标签: python file io readfile


【解决方案1】:

我们可以使用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

【讨论】:

    【解决方案2】:
    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
    

    【讨论】:

    【解决方案3】:
    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

    【讨论】:

    • 我得到了问题:文件“MergeANNOVARResults.py”,第 10 行,open(refseq) 作为 refseq_fh,open(gencode) 作为 gencode_fh: ^ SyntaxError: invalid syntax
    • 这会将所有 textfile1 和 textfile2 加载到内存中吗?
    【解决方案4】:

    Python 确实允许您逐行读取,这甚至是默认行为 - 您只需像遍历列表一样遍历文件。

    wrt/ 一次迭代两个可迭代对象,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())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多