[Tutor] How to skip to next line in for loop

Paul McGuire ptmcg at austin.rr.com
Fri May 2 17:42:28 CEST 2008


Augghh!  I can't stand it!!!  If position is a boolean, then *why* must we
test if it is equal to True?!!!  It's a boolean!  Just test it!  For that
matter, let's rename "position" to something a little more direct,
"print_line" perhaps?

Did you know that files are now iterators?  If going through the file line
by line, no need for read().split(), or readlines(), or anything else, just
iterate over f:

f=open('file.txt',r)
print_line = False
for line in f:
   if print_line:
         print line
         print_line = False
   if line == "3":
         print_line = True
f.close() 


Is there only one line containing a "3" in this file?  What if that were the
3rd line in a file containing 50 zillion lines?  After printing the line
after "3", this program iterates through the whole rest of the file, for
nothing.  Nothing!  If you only want the first (or only) line after the line
containing "3", then do:

f=open('file.txt',r)
print_line = False
for line in f:
    if print_line:
        print line
        # found it, no need to read any further
        break  
    if line == "3":
        print_line = True
f.close()

-- Paul



More information about the Tutor mailing list