, - :
f = open('somefile.txt')
lines = f.read().splitlines()
for current_line, next_line in zip(lines, lines[1:]):
print current_line
print next_line
print '-------'
zip , .
: , itertools :
import itertools
f = open('somefile.txt')
i1, i2 = itertools.tee(f)
lines = itertools.izip(i1, itertools.islice(i2, 1, None))
for current_line, next_line in lines:
print current_line
print next_line
print '-------'
:
itertools.tee used to create two independent iterators (one for the current line and one for the next line) that use the original file iterator.itertools.slice used to start the next iterator of the line in the second line.itertools.izip used to combine the results of both iterators row by row in a tuple.
Edit 2: as @eyquem suggested, you can also open the file twice:
import itertools
f = open('somefile.txt')
g = open('somefile.txt')
lines = itertools.izip(f, itertools.islice(g, 1, None))
for current_line, next_line in lines:
print current_line
print next_line
print '-------'
source
share