Newbie question about file input

Ben Last ben at benlast.com
Mon Aug 16 17:50:07 CEST 2004


Just the sort of problem to muse over whilst having a cup of tea :)
> Basically every game starts with the [Event "..."] header and then the
> information about the game is given.

An entirely blank line signals the end of file (from the Python
documentation on readline(): "An empty string is returned only when EOF is
encountered immediately".  Otherwise the string will end with a newline
(probably "\n").  Try your loop as:
while 1:
  line = zf.readline()

  #If line is entirely empty, exit the loop; we've met EOF
  if not line:
    break

  #Strip any whitespace and split the line.  A line that contains
  #only whitespace will result in an empty list being returned from
  #split, so test for that.
  ls = line.strip().split()
  if ls and ls[0] == "[Event":
     games += 1

zf.close()

On the other hand, I'm guessing that the reason you're splitting the line is
to look at the first word.  There are alternative ways to do this:
  if line.startswith("[Event"):
or
  if line.find("[Event") >= 0:
Either would cope with the line being empty, or containing just whitespace.

Ok, so if all you want to do is to count the number of games, you can count
the number of lines that contain "[Event...":

#Simple way
zf=open('test.pgn','r')
count = 0
for line in zf.readlines():
  if line.startswith("[Event"):
    count = count + 1
zf.close()

Or:

#More exotic way, using a list comprehension
zf=open('test.pgn','r')
count = len([x for x in zf.readlines() if x.strip().startswith("[Event")])
zf.close()

That's gratuitously clever, though :)

regards
b

> 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?
>
>
>
>
>
> --
> Aaron Deskins
> Graduate Student
> Chemical Engineering
> Purdue University
> --
> http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list