同时读取两个文本文件-python [英] Read two textfile line by line simultaneously -python
问题描述
有没有办法读取文件,行同时?
以下是文件的外观样本,可以想像每个文件的行数约为1,000,000。
textfile1:
这是英文$的第一行b $ b这是英语中的第二行
这是英文的第三行
textfile2:
C'est lapremièreligne enFrançais
C'est ladeuxièmeligne enFrançais
C'est latroisièmeligne enFrançais
所需的输出
这是英语中的第一行。\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ ladeuxièmeligne enFrançais
这是英语中的第三行。\tC'est latroisièmeligne enFrançais
此版本有一个java版本的读取两个文本文件同时一行一行-java ,但python不使用逐行读取的bufferedreader 。那么该怎么做?
from itertools import izip
打开(textfile1)为textfile1,打开(textfile2)为textfile2:
为x,y为izip(textfile1,textfile2):
x = x.strip()
y = y.strip()
print({0} \t {1}。format(x,y))
在Python 3中,使用内置的 zip $ c $替换
itertools.izip
c>。
I have 2 textfiles in two different languages and they are aligned line by line. I.e. the first line in the textfile1 should be equals to the first line in textfile2, and so on and so forth.
Is there a way to read both file line-by-line simultaneously?
Below is a sample of how the files should look like, imagine the number of lines per file is around 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
desired output
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
There is a java version of this Read two textfile line by line simultaneously -java, but python doesn't use bufferedreader that reads line by line. So how would it be done?
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))
In Python 3, replace itertools.izip
with the built-in zip
.
这篇关于同时读取两个文本文件-python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!