Leer dos archivos de texto línea por línea simultáneamente-python


Tengo 2 archivos de texto en dos idiomas diferentes y están alineados línea por línea. Es decir, la primera línea en el textfile1 debe ser igual a la primera línea en textfile2, y así sucesivamente y así sucesivamente.

¿Hay una manera de leer ambos archivos línea por línea simultáneamente?

A continuación se muestra una muestra de cómo deberían verse los archivos, imagine que el número de líneas por archivo es de alrededor de 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

Salida Deseada

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

Hay una versión java de este Leer dos textfile línea por línea simultáneamente-java, pero python no utiliza bufferedreader que lee línea por línea. Entonces, ¿cómo se haría?

Author: Community, 2012-07-02

3 answers

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))

En Python 3, reemplace itertools.izip con el zip incorporado.

 77
Author: Fred Foo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-02 14:21:55
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()))

Salida:

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
 15
Author: Ashwini Chaudhary,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-17 16:58:41

Python le permite leer línea por línea, e incluso es el comportamiento por defecto - usted solo itera sobre el archivo como iteraría sobre una lista.

Wrt/ iterando sobre dos iterables a la vez, itertools.izip es tu amigo:

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())
 3
Author: bruno desthuilliers,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-02 14:03:32