Reputation: 6927
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.
Upvotes: 5
Views: 5743
Reputation: 82924
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
Upvotes: 5
Reputation: 66930
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:
for line in file:
line = line.strip()
llist = line.split()
if llist and llist[0] == 'NUMS':
for line in file:
line = line.strip()
if line == 'END':
break
else:
print line,
print # newline
Read up on how iterators work for more information.
Upvotes: 5