alv*_*vas 51 python io file readfile
我有两种不同语言的文本文件,它们是逐行对齐的.即textfile1中的第一行对应于textfile2中的第一行,依此类推.
有没有办法同时逐行读取这两个文件?
下面是文件应该如何显示的示例,假设每个文件的行数大约为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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
期望的输出
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
Run Code Online (Sandbox Code Playgroud)
这个Read两个文本文件的Java版本同时逐行-java,但Python不使用逐行读取的bufferedreader.那怎么办呢?
Fre*_*Foo 94
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))
Run Code Online (Sandbox Code Playgroud)
在Python 3中,替换itertools.izip为内置zip.
Ash*_*ary 17
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()))
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
我们可以使用它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]))
Run Code Online (Sandbox Code Playgroud)
笔记:
python 3代码。对于,像其他人说的那样python 2使用。itertools.izipzip将在迭代最短文件后停止,itertools.zip_longest如果重要则使用。