Newbie question about file input

Christopher T King squirrel at WPI.EDU
Mon Aug 16 11:46:12 EDT 2004


On Mon, 16 Aug 2004, Aaron Deskins wrote:

> Basically every game starts with the [Event "..."] header and then the 
> information about the game is given.
> 
> 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
> 
> 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 immediate fix is to check for newlines, in addition to blank strings:

     if line == '' or line =='\n':
         break

The not-so-immediate fix would be to skip the blank line check, and 
instead check the length of ls:

     if len(ls) and ls[0] == '[Event':

But perhaps a better fix would be to skip the split and use the 
str.startswith() method:

     if line.startswith('[Event'):

This won't fail in the case of a blank line, and will be somewhat faster 
than str.split().

There are, of course, even better fixes (such as using regexes or 
PyParsing), but they would likely be overkill unless you plan on 
extracting more data from the file (such as the name of the event).

Hope this helps.




More information about the Python-list mailing list