How to read forward in a file when going through it using Python?

I look through the file and, if I find something, I would like to read a few lines that are looking for something before returning control to the main loop. However, I want to regain control at the moment when I stopped looking into the future.

Code example:

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. 

Input Example:

 NUMS 1 2 3 4 5 END SOME MORE STUFF NUMS 6 7 8 9 0 END 

Required Conclusion:

 1 2 3 4 5 6 7 8 9 0 

I am new to Python, so if there is a better way to do this, besides using a loop to look forward, I'm glad to see it.

+6
source share
2 answers

When you iterate over open files, you can only get each line exactly once. This is not like lists, where each loop of the loop gets its own iterator throughout the list.

You can have the inner loop β€œsteal” from the file, so the outer loop will not 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 

Learn more about how iterators work for more information.

+4
source

It is not recommended to read further if you do not need it, which is here. What you need to do can be done in a single loop, maintaining one status bit. This allows you to check errors , and scales to more complex requirements than can be handled by nested loops on 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 
+4
source

Source: https://habr.com/ru/post/901853/


All Articles