How to iterate across lines in two files simultaneously?
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
.
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