Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

python - Reading two text files line by line simultaneously

I have two text files in two different languages and they are aligned line by line. I.e. the first line in textfile1 corresponds 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 EnglishC'est la première ligne en Fran?ais
This is a the 2nd line in EnglishC'est la deuxième ligne en Fran?ais
This is a the third line in EnglishC'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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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}{1}".format(x, y))

In Python 3, replace itertools.izip with the built-in zip.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...