Newbie question about file input

Aaron Deskins ndeskins at ecn.purdue.edu
Mon Aug 16 11:16:11 EDT 2004


Hello everyone,
   I'm trying to make a simple python script that will read a text file 
with a bunch of chess games and tell me how many games there are. The 
common format for such chess games is the .pgn format (which is just a 
text file) with the following being typical (with the following file 
having 2 games):

[Event "Quizzes"]
[Site "?"]
[Date "????.??.??"]
[Round "?"]
[White "?"]
[Black "?"]
[Result "*"]
[SetUp "1"]
[FEN "6k1/5p2/8/4p3/pp1qPn2/5P2/PP2B3/2Q2K2 b - - 0 1"]
[PlyCount "5"]

1... Qg1+ 2. Kxg1 Nxe2+ 3. Kf1 Nxc1 *

[Event "Quizzes"]
[Site "?"]
[Date "????.??.??"]
[Round "?"]
[White "?"]
[Black "?"]
[Result "*"]
[SetUp "1"]
[FEN "8/r4pbk/4p2p/8/p5R1/Pq3N1P/1P1Q1PP1/6K1 w - - 0 1"]
[PlyCount "5"]

1. Rxg7+ Kxg7 2. Qd4+ Kf8 3. Qxa7 *


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?





-- 
Aaron Deskins
Graduate Student
Chemical Engineering
Purdue University



More information about the Python-list mailing list