Rob Avery IV Rob Avery IV - 2 months ago 15
Python Question

Python: For loop with files, how to grab the next line within forloop?

I have a file that I want to get each line at a time, but once it gets to a specific line, I need to get the next few lines information.

Here is a code sample:

rofile = open('foo.txt', 'r')
for line in rofile:
print line
if(line.strip() == 'foo'):
line =
print line
line =
print line
line =
print line

When I come back around and loop for the second time, that first print statement should print the 5th line in the file. Is there any possible way to do this?

EDIT: Sorry for not clarifying the details.
is a file object that I'm iterating through. Whether
is the real method to obtain the next line when using a file, I don't know. I don't have much experience with file manipulation in python.


You can use iter to convert your object into an iterable which supports next.

irofile = iter(rofile)
for line in irofile:
    print line
    if(line == 'foo'):
        line = next(irofile)  #BEWARE, This could raise StopIteration!
        print line

As pointed out in the comments, if your object is already an iterator, then you don't need to worry about iter (this is the case with file objects). However, I leave it here as it works for the case of any arbitrary iterable (e.g. lists).