Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = line.next()
        print line
        line = line.next()
        print line
        line = line.next()
        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. rofile is a file object that I'm iterating through. Whether next() 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.

like image 442
Rob Avery IV Avatar asked Nov 26 '12 19:11

Rob Avery IV


People also ask

How do you go to the next line in a for loop in Python?

Python file method next() is used when a file is used as an iterator, typically in a loop, the next() method is called repeatedly. This method returns the next input line, or raises StopIteration when EOF is hit.

How do you get the next element in a for loop?

Use enumerate() function to access the next item in a list in python for a loop. The for loop allows to access the variables next to the current value of the indexing variable in the list.

How do you move to the next line in a text file in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text. You can print strings without adding a new line with end = <character> , which <character> is the character that will be used to separate the lines.


1 Answers

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).

like image 187
mgilson Avatar answered Oct 01 '22 02:10

mgilson