配列 - python 複数ファイル 読み込み
同時に2つのテキストファイルを1行ずつ読む-python (2)
私は2つの異なる言語で2つのテキストファイルを持っていて、行ごとに整列しています。 つまり、textfile1の最初の行はtextfile2の最初の行と等しくなければなりません。
両方のファイルを同時に1行ずつ読み込む方法はありますか?
以下は、ファイルがどのように見えるかのサンプルです.1ファイルあたりの行数が約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
このjava版がありますが、 同時に2行のテキストファイルを1行ずつ読み込みます。- javaですが、pythonは1 行ずつ読み込むbufferedreaderを使用しません。 それでどうやってやるの?
Pythonでは行単位で読み込むことができますが、これはデフォルトの動作でもあります。リストを反復処理するようにファイルを繰り返し処理するだけです。
一度に2つのiterableをwrt / iterating、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())
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
に置き換えます。