File iteration, line existence check

I am reading a file using a for loop like this ...

f = open("somefile.txt")

for line in f:
    do stuff

with the exception of every line I read, I need to take an element from the line in front and put it in the current line. What is the best way to do this? Is there a way to read the next line or get some element from it without reading it?

+5
source share
4 answers

If my understanding is correct, and you want to work with each line in turn, using some value from the next line, my suggestion will simply store the value that you are reading now and work with the last value. Work in the opposite direction is last_lineyour current line, and the line is the next.

last_line = None

with open("somefile.txt") as f:
    for line in f:
        if not last_line == None:
            do_stuff(last_line, extract_needed_part(line))
        last_line = line
do_stuff(last_line) #The final line without anything following it.

n n + 1 n-1 n. .

, .

+6

, :

f = open("somefile.txt")
lines = f.readlines()
f.close()

for index, value in enumerate(lines):
    # Check if next line exists
    if index + 1 > len(lines):
        next_line = lines(index + 1)
        # do something with line and next_line

Edit:

:

f = open("somefile.txt")
previous_line = f.readline()
for line in f:
    # Do something with line and previous_line
    print(line, previous_line)
    # Save this line for the next iteration
    previous_line = line

, , . .

, , .

+3

, - :

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 '-------'
0
source
with open('somefile.txt') as f, open('somefile.txt') as g:
    g.readline()
    lines = ( (f.readline(),line) for line in g)
        for precline,aheadline in lines:
            # do what you want
0
source

All Articles