kravemir kravemir - 1 month ago 5x
Python Question

Is possible to iterate file by two lines?

Possible Duplicate:

reading lines 2 at a time

In python we can iterate over file line by line. But what if i want iterate by two lines?

f = open("filename")
for line1, line2 in ?? f ??:
do_stuff(line1, line2)


You could do something like this:

with open('myFile.txt') as fh:
  for line1 in fh:
    line2 = next(fh)

    # Code here can use line1 and line2.

You may need to watch for a StopIteration error on the call to next(fh) if you have odd lines. The solutions with izip_longest are probably better able to avoid that need.