-5
with open('myfile.txt') as f:
    for line in f: 
        doSomething(line)

Is there a way to iterate through two files at once? Here's some pseudo code to help you understand..

with open('myfile.txt') as f: and with open ('myfile2.txt') as d:
    for line in f and for line2 in d:
        doSomething(line, line2)
user3412816
  • 53
  • 1
  • 8

1 Answers1

4
with open('myfile.txt') as f, open('myfile2.txt') as d:
    for line1, line2 in zip(f, d):
        do_something(line1, line2)

Note that, for Python 2, you should use itertools.izip - it only holds one pair of lines in memory at a time, rather than returning a list of all pairs of lines.

Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99