1

I have the following script:

iterator = iter(f.splitlines())
for line in iterator:
    if "some_string" in line:
        next_line = next(iterator) # next line has some float/integer values
        if next_line == "some_value":
            do-something

I am opening a file and looking for a keywords in it. If I find them, I append the integer/float value that comes in the next line to a list.

The problem is that the "for" loop will take the line that comes after "next_line". For example:

line1: "keyword"
line2: 3
line3: something-else
line4: keyword
line5: 4

if I found what I want in line1 and took the ineger from line2, "for-loop" will continue from line 3. How can make it continue from the last place that line1 was (continue from line2 regardless that next_line took it)? I want to go one line back.

Omar
  • 557
  • 2
  • 6
  • 23
  • possible duplicate of [seek() function?](http://stackoverflow.com/questions/11696472/seek-function) – user Apr 23 '15 at 18:35
  • It is definitely not a duplicate of the seek() function question. Seek deals with moving back/forward in units of bytes. It seems the asker (at least from the answer we got) is trying to move forward/back a line at a time. – Azendale Feb 17 '17 at 01:53

1 Answers1

1

It sounds like you want to use itertools.tee to get two iterators that can be set to be one item off from each other:

import itertools

it0, it1 = tee(f)   # no need for splitlines, just use the file object as an iterator

next(it1)   # throw away the first value from one of the iterators

for val0, val1 in zip(it0, it1):   # iterate in parallel
    if "some_string" in val0 and val1 == "some_value":
        do_stuff()
Blckknght
  • 100,903
  • 11
  • 120
  • 169