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.
When you loop over open files, you can only get each line exactly one time. This is unlike lists, where each for loop would get its own iterator over the entire list.
You can have an inner loop “steal” lines from the file, so that the outer loop doesn’t get to see them:
Read up on how iterators work for more information.