This might be a really dumb question, however I've looked around online, etc. And have not seen a solid answer.
Is there a simple way to do something like this?
lines = open('something.txt', 'r').readlines() for line in lines: if line == '!': # force iteration forward twice line.next().next() <etc>
It's easy to do in C++; just increment the iterator an extra time. Is there an easy way to do that in Python?
I would just like to point, out the main purpose of this question is not about "reading files and such" and skipping things. I was more looking for C++ iterator style iteration. Also the new title is kinda dumb, and i dont really think it reflects the nature of my question.
The continue statement in Python is used to skip the rest of the code inside a loop for the current iteration only. In other words, the loop will not terminate immediately but it will continue on with the next iteration. This is in contrast with the break statement which will terminate the loop completely.
In Python, the break statement provides you with the opportunity to exit out of a loop when an external condition is triggered. You'll put the break statement within the block of code under your loop statement, usually after a conditional if statement.
Try to add continue; where you want to skip 1 iteration. Unlike the break keyword, continue does not terminate a loop. Rather, it skips to the next iteration of the loop, and stops executing any further statements in this iteration.
In Python, you can use the optional 'step' parameter to skip numbers in a range. If you are using a range object in a loop, the 'step' parameter will allow you to skip iterations.
Try:
lines = iter(open('something.txt', 'r')) for val in lines: if val == "!": lines.next() continue <etc>
You may want to catch StopIteration
somewhere. It'll occur if the iterator is finished.
The file.readlines method returns a list of strings, and iterating over a list will not let you modify the iteration in the body of the loop. However if you call iter on the list first then you will get an iterator that you can modify in the loop body:
lines = open('something.txt', 'r').readlines() line_iter = iter(lines) for line in line_iter: if line == '!': # force iteration forward twice line_iter.next() line_iter.next() <etc>
As ebo points out the file object itself acts as an iterator, so you can get the same effect by not calling readlines and leaving out the call to iter.
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