Tutorial :How can I skip the current item and the next in a Python loop?


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.



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.


This is short, pythonic, and works:

with open('something.txt', 'r') as f: # or simply f = open('something.txt', 'r')      nobang = (line for line in f if line != '!\n')      for line in nobang:          #...  


As many observed, this is not the solution yet. The best I can think of is a combination of what is already on this page:

with open('something.txt', 'r') as f:      for line in f:          if line == '!\n':              next(f,None) # consume next line              continue # skip this line          # ...  


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.


Not very compact:

skip = False  for line in open('something.txt'):    if skip:      skip = False      continue      if line.strip() == '!':      skip = True      continue  


You could use recursion

input = iter( open('something.txt') )  def myFunc( item ):      val = iter.next()      if( val == '!' ):          item.next()          return myFunc( item )      #continue on with looping logic  

Editted post contained the following which actually didn't answer your question:

Have you tried

[line for line in open('something.txt') if line != '!']  

to produce a new list? Or even better

filter( lambda line: line != '!', open('something.txt') )  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »