python一次读取多个文件_同时读取两个文本文件-python

1586010002-jmsa.png

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.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值