Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate across lines in two files simultaneously?

Tags:

I have two files, and I want to perform some line-wise operation across both of them. (In other words, the first lines of each file correspond, as do the second, etc.) Now, I can think of a number of slightly cumbersome ways to iterate across both files simultaneously; however, this is Python, so I imagine that there is some syntactic shorthand.

In other words, is there some simple way to adapt the

for line in file: 

so that it pulls data from both files simultaneously?

like image 275
chimeracoder Avatar asked Jul 23 '10 21:07

chimeracoder


People also ask

How do I read two files at once in Python?

Steps Needed Steps used to open multiple files together in Python : Both the files are opened with open() method using different names for each. The contents of the files can be accessed using readline() method. Different read/write operations can be performed over the contents of these files.

Can I iterate through a list?

You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.


2 Answers

Python 2:

Use itertools.izip to join the two iterators.

from itertools import izip for line_from_file_1, line_from_file_2 in izip(open(file_1), open(file_2)): 

If the files are of unequal length, use izip_longest.

In Python 3, use zip and zip_longest instead. Also, use a with to open files, so that closing is handled automatically even in case of errors.

with open(file1name) as file1, open(file2name) as file2:     for line1, line2 in zip(file1, file2):         #do stuff 
like image 123
Daniel Roseman Avatar answered Sep 22 '22 22:09

Daniel Roseman


You could try

for line1, line2 in zip(file1, file2):     #do stuff 

Careful though, this loop will exit when the shorter file ends.

When using Python 2, itertools.izip is better for this sort of thing because it doesn't create a list.

like image 21
Alex Bliskovsky Avatar answered Sep 18 '22 22:09

Alex Bliskovsky