I am looping through a file and if I find something, would like to read ahead several lines looking for something before returning control to the main loop. However, I want to return control at the point that I stopped looking ahead.
Sample code:
for line in file:
line = line.strip()
llist = line.split()
if llist[0] == 'NUMS':
# some loop to read ahead and print nums on their own line
# until it finds END, then return control to the main for
# loop at the point where it stopped looking ahead.
Sample input:
NUMS
1
2
3
4
5
END
SOME
MORE
STUFF
NUMS
6
7
8
9
0
END
Desired output:
1 2 3 4 5
6 7 8 9 0
I am fairly new at Python, so if there is a better way to do it besides using a loop for look ahead, I'm happy to see it.
Python File next() Method 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.
To do that, first, open the file using Python open() function in read mode. The open() function will return a file handler. Use the file handler inside your for-loop and read all the lines from the given file line by line. Once done,close the file handler using close() function.
The readlines () method is the most popular method for reading all the lines of the file at once. This method reads the file until EOF (End of file), which means it reads from the first line until the last line. When you apply this method on a file to read its lines, it returns a list.
Python provides the ability to open as well as work with multiple files at the same time. Different files can be opened in different modes, to simulate simultaneous writing or reading from these files.
It's not a good idea to read ahead if you don't need to, which is the case here. What you need to do can be accomplished in a single for loop, by maintaining one bit of state. This allows for error checking, and scales up to much more complicated requirements than can be handled by nested loops over the same iterator.
guff = """NUMS
1
2
etc etc
9
0
END"""
state = ""
for item in guff.split():
if item == "NUMS":
if state == "NUMS": print "missing END"
state = "NUMS"
elif item == "END":
if state == "": print "missing NUMS"
state = ""
print
elif state == "NUMS":
print item,
if state == "NUMS": print # missing END
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