[Tutor] skipping lines

camartin at snet.net camartin at snet.net
Thu Oct 9 18:11:14 EDT 2003


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

I've tried using an  if statement on not empty line(like I can do in 
MatLab) and I've tried a bunch of other things but I've not been 
successful.  This seems so trivial but I'm not getting it.

Thanks in advance.

Cliff







   





More information about the Tutor mailing list