2012-07-02 42 views
32

我有兩種不同語言的2個文本文件,並且它們是逐行對齊的。即textfile1中的第一行應該等於textfile2中的第一行,依此類推。同時讀取兩個文本文件--python

有沒有辦法同時讀取兩個文件的文件?

下面是文件應該是什麼樣子的示例,想象一下每個文件的行數大約爲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 

所需的輸出

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讀取線按行。那麼它將如何完成?

+3

這不是Python,但如果你只需要在一個新的文件輸出,'粘貼textfile1 textfile2> output'也應該工作。 – eumiro

+0

如果你喜歡larsmans的回答,你可能想把它標記爲已接受。 –

回答

64
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

+0

謝謝,它的工作就像一個魅力 – alvas

+0

我得到的問題: 文件 「MergeANNOVARResults.py」,用開(以RefSeq)線10 爲refseq_fh,開(gencode)爲gencode_fh: ^ 語法錯誤:無效的語法 – jmtoung

13
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 
+2

請注意,zip()會將兩個文件的全部內容拉入內存(在Python 2.x中) –

+0

更好地使用['from itertools import izip'](http://docs.python.org/library/itertools。 html#itertools.izip)或['izip_longest'](http://docs.python.org/library/itertools.html#itertools.izip_longest)。 –

+2

+1雖然使用'與'。 –

3

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