Newbie question about file input

Peter Hansen peter at engcorp.com
Mon Aug 16 11:42:53 EDT 2004


Aaron Deskins wrote:

> My first attempt at the python script is:
> 
> #! /usr/bin/env python
> import string
> import sys
> zf=open('test.pgn','r')
> # games is number of games
> games = 0
> while 1:
>  line = zf.readline()
>  if line == '':
>    break
>  ls = line.split()
>  print ls[0]
>  if ls[0] == '[Event':
>   games+=1
> zf.close()
> print games

Small note: it would make your code more readable and thus
easier to comment on if you followed convention and used four
spaces for indentation.  Your volunteer tutors thank you! :-)

> I'm having problems when the script reads a blank line from the pgn 
> file. I get the following error message:
>   IndexError: list index out of range
> The problem is that ls[0] does not exist when a blank line is read. What 
> would be the best way of fixing this?

The "best" way might be just to check for and ignore blank lines prior
to the rest of the code that might fail when you find one:

while 1:
     line = zf.readline()
     if not line:
         break   # more idiomatic, perhaps, than if line == ''

     # remove leading and trailing whitespace, including newline
     line = line.strip()
     if not line:
         continue  # don't break, go back for another

     # from here on line is guaranteed not to be blank


Another approach might be to use exceptions, though I wouldn't
really recommend it here since the above is fairly idiomatic,
I believe:

while 1:
     # blah blah
     ls = line.split()
     try:
         if ls[0] == '[Event':
             # blah
     except IndexError:
         # blank line, so no first field, so continue
         continue


You might also consider using "ls.startswith('[Event')"
instead, as that avoids the need to split the line at
all, but you're doing fine on your own so far.  (Not that
this will stop someone from posting a one-liner using
the "re" module and len(findall()), but you can safely
ignore them. ;-)

-Peter



More information about the Python-list mailing list