File Access Looks Ahead

I need to read the file line by line, and I need to look at the "next line", so first I read the file in the list, and then go to the list ... somehow it seems rude, creating a list can become expensive.

for line in open(filename, 'r'):
    lines.append(line[:-1])

for cn in range(0, len(lines)):
    line = lines[cn]
    nextline = lines[cn+1] # actual code checks for this eof overflow

there should be a better way to iterate over the lines, but I don't know how to look ahead

+5
source share
3 answers

You might be looking for something like a pairing recipe from itertools.

from itertools import tee, izip
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

with open(filename) as f: # Remember to use a with block so the file is safely closed after
    for line, next_line in pairwise(f):
        # do stuff
+6
source

You could do it that way

last_line = None

for line in open(filename):                                                                  
    if last_line is not None:
        do_stuff(last_line, line) 
    last_line = line                                                        
+1
source

You can create iteratorand do it as follows:

f = open(filename, 'r')
g = open(filename, 'r')

y = iter(g.readlines())
y.__next__()

for line in f:
    print(line)
    try:
        print(y.__next__())
    except StopIteration:
        f.close()
        g.close()
0
source

All Articles