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.
source share