views:

53

answers:

2

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?

+4  A: 

You could try

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

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

Edit: izip is better for this sort of thing. See Daniel's answer.

Alex Bliskovsky
+6  A: 

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.

Daniel Roseman
+ for using izip instead of zip
zvonimir