IndexError: string index out of range
michael
mhyoung at valdosta.edu
Thu Apr 12 19:07:00 EDT 2001
#!/usr/bin/python
import sys
FILENAME = "./testfile"
EXCLUDE='#' #Lines beginning with this should not be printed.
def get_line() :
buf = f.readline()
if (buf[0] == EXCLUDE):
return 0
else:
return buf
f = open(FILENAME, "r")
while 1:
buf = get_line()
if (buf == ''):
break
if (buf == 0): # If 0 is returned then the line read on this loop
begins with
continue # the EXCLUDE char and is not to be printed
else:
sys.stdout.write(buf)
f.close()
############# END OF PROGRAM ##############
Im new to Python.This is my prgram. It reads the contents of testfile
line by line and prints it out unless the line begins with a #. I know
that it might be pointless to use a function for this but it is for
learning purposes. This program works fine until it gets to the last
line in the testfile and I get this error.
Traceback (innermost last):
File "./test3.py", line 18, in ?
buf = get_line()
File "./test3.py", line 10, in get_line
if (buf[0] == EXCLUDE):
IndexError: string index out of range
Can someone please tell me what I'm doing wrong? I've looked all over
the net and in several books for a solution.
TIA , Michael
More information about the Python-list
mailing list