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.
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.
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.
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.
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. list
s).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With