[Tutor] skipping lines

Jeff Shannon jeff at ccvcorp.com
Thu Oct 9 20:29:24 EDT 2003


camartin at snet.net wrote:

>   for line in f.xreadlines():
>    words = line.rstrip().split()
>    S = words[9]
>    print >>g,S

> Traceback (most recent call last):
>  File 
> "C:\Python23\lib\site-packages\Pythonwin\pywin\framework\scriptutils.py", 
> line 310, in RunScript
>    exec codeObject in __main__.__dict__
>  File "C:\Python23\Script2.py", line 16, in ?
>    S = words[9]
> IndexError: list index out of range

You could always explicity catch the IndexError --

for line in f.xreadlines():
     words = line.rstrip().split()
     try:
         S = words[9]
         print >>g, S
     except IndexError:
         pass

This should have the effect of ignoring empty lines.  Another 
possibility is to test line itself, as you said you tried.

for line in f.xreadlines():
     if line.strip():
         words = line.rstrip().split()
         # ...

The key here is that Python considers an empty string ("") to be 
equivalent to 'false'.  We can't just test line directly, because it 
will contain at least a newline, and possibly other whitespace. 
line.strip() will get rid of all of that, leaving an empty string for 
a blank line.

This could perhaps be rearranged to be a tiny bit more efficient --

for line in f.xreadlines():
     line = line.strip()
     if line:
         words = line.split()
         # ...

The difference here is that you're only strip()ing once, but this will 
also strip off leading whitespace.  This could be an issue if leading 
whitespace is significant (as it is in, say, Python sourcecode files). 
  For the purpose you seem to be describing, though, it should be fine.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Tutor mailing list