Is there a better way to read lines two at a time from a file in python than:
with open(fn) as f:
for line in f:
try:
line2 = f.next()
except StopIteration:
line2 = ''
print line, line2 # or something more interesting
I’m in 2.5.4. Anything different in newer versions?
EDIT: a deleted answer noted: in py3k you’d need to do next(f) instead of f.next(). Not to mention the print change
Alas,
izip_longestrequires Python 2.6 or better; 2.5 only hasizip, which would truncate the last line iffhas an odd number of lines. It’s quite easy to supply the equivalent functionality as a generator, of course.Here’s a more general “N at a time” iterator-wrapper:
itertoolsis generally the best way to go, but, if you insisted on implementing it by yourself, then:In 2.5, I think the best approach is actually not a generator, but another itertools-based solution:
(since 2.5 doesn’t have the built-in
next, as well as missingizip_longest).