2

I have a loop like the following:

with open(file, 'r') as f:
    next(f)
    for line in f:
        print line

But I don't want to print just the current line with each iteration, I want to also print the previous line like below, but the code doesn't give me what I am looking for:

with open(file, 'r') as f:
    next(f)
    for line in f:
        previous(f)    #this does not go to the previous line
        print line
        next(f)
        print line
        next(f)

Result should be like this:

Input:

line1
line2
line3

Output:

line1
line2
line2
line3
The Nightman
  • 5,609
  • 13
  • 41
  • 74

1 Answers1

6

Iterators can only go forward, so there is no previous() function.

Just store the current line in a variable; it'll be the previous by next iteration:

with open(file, 'r') as f:
    previous = next(f)
    for line in f:
        print previous, line
        previous = line
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • This was something I was trying, but if you do `previous=next(f)` that should store line 2 right? How can I store line 1 when first iterating through? – The Nightman Jun 17 '15 at 15:52
  • 1
    @TheNightman: `previous = line`. `line` is the *current line*, it'll be the previous line the next time you use `next()` (directly or by leaving iteration to the `for` loop). – Martijn Pieters Jun 17 '15 at 15:55
  • actually this works perfectly. Thanks for the help – The Nightman Jun 17 '15 at 15:56