Is it possible to iterate a file in two lines?

Possible duplicate:
reading lines 2 at a time

In python, we can iterate over a file line by line. But what if I want iteration in two lines?

f = open("filename") for line1, line2 in ?? f ??: do_stuff(line1, line2) 
+4
source share
3 answers

You can 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 observe the StopIteration error when calling next(fh) if you have odd lines. Solutions with izip_longest are probably better able to avoid this need.

+2
source

Use the grouper function from itertools recipes .

 from itertools import zip_longest def grouper(n, iterable, fillvalue=None): "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return zip_longest(fillvalue=fillvalue, *args) f = open(filename) for line1, line2 in grouper(2, f): print('A:', line1, 'B:', line2) 

Use zip instead of zip_longest to ignore the odd line at the end.

The zip_longest function was named izip_longest in Python 2.

+5
source
 f = open("file") content = f.readlines() print content[0] #You can choose lines from a list. print content[1] 

This is one way to do this. Now you can simply iterate over the list with the for loop and do whatever you want with it, or explicitly select the lines.

+1
source

All Articles