Odczyt dwóch plików tekstowych linia po linii jednocześnie-python

Mam 2 pliki tekstowe w dwóch różnych językach i są wyrównane linia po linii. Tzn. pierwsza linia w textfile1 powinna być równa pierwszej linii w textfile2, i tak dalej i tak dalej.

Czy istnieje sposób na jednoczesne odczytywanie obu plików linia po linii?

Poniżej znajduje się przykład jak pliki powinny wyglądać, wyobraź sobie, że liczba linii na plik wynosi około 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

Pożądane wyjście

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

Istnieje wersja java tego odczytująca dwa pliki tekstowe linia po linii jednocześnie-java, ale python nie używa programu bufferedreader, który odczytuje linię po linii. Więc jak to się robi?

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

W Pythonie 3 zastąp itertools.izip wbudowanym zip.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
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()))

Wyjście:

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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-03-17 16:58:41

Python pozwala Ci czytać wiersz po wierszu i jest to nawet domyślne zachowanie - po prostu iteratuj nad plikiem, tak jak iteratuj nad listą.

Wrt / iteracja dwóch iterabli naraz, itertools.izip jest twoim przyjacielem:

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/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-02 14:03:32