[Tutor] skipping lines

Anna Ravenscroft anna at aleax.it
Thu Oct 9 18:39:13 EDT 2003


On Friday 10 October 2003 12:11 am, camartin at snet.net wrote:
> I have a piece of code that reads in a file line by line into lists. It
> then processes the file list by list and writes out the file processed
> line by processed line.  This works fine unless I have a blank line.  An
> example of the code (the actual code is more complicated but it works
> unless there are blank lines) is shown below,
>
> # file to open CSV files or plain delimited text. As one reads
> # each line convert the date to ordinal number, then write out
> # the line into a CSV file
> from datetime import date
> import string
> from string import *
>
>
> filename = raw_input("Enter the filename(make sure you enter the full
> path): ")
> f = open(filename,'r')
> g = open("c:\python23\outtest3.txt", 'w')
>
>
> for line in f.xreadlines():
>     words = line.rstrip().split()
>     S = words[9]
>     print >>g,S
>
>
> f.close()
> g.close()
>
>
> As I said above this writes what I expect but the error message I get is
> what one expects for a blank line namely there is no index S[9].
>
> 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
>

What about this:
(untested)

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

The idea is to catch the exception so you can pass (ignore) it and go on to  
do the next line in your for loop. 

Anna
-- 
There is a type 3 error in which your mind goes totally blank whenever you try 
to remember which is which of type 1 and type 2.
                                                 -Richard Dawkins




More information about the Tutor mailing list