Banana Banana - 7 months ago 11
Python Question

Python list index error (student files)

I am having problem with a list for an averaging program, it says:

'line 20, in
nameletter = (letter[int(num)])
IndexError: list index out of range'

This is the part of the code:

f2 = open("Classes" + "/Sorted/" + "Alphabetical.txt", "w")

letter = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']

print(letter[num])

#Loop
while num <= 26:
nameletter = (letter[int(num)])
if os.path.exists("Classes" + "/" + nameletter + ".txt"):
#Opening the students file
f = open("Classes" + "/" + nameletter + ".txt")
List = f.read().splitlines()
f.close()
#Writing data to the file
f2.write(List[5] + " - score = " + List[6])
f2.write("\n")
else:
pass
num = int(num) + 1
f2.close()

Answer

Lists are indexed from 0. So the last index of your letters is 25 not 26. But better use a for-loop, then you don't have to count by hand:

import string
f2 = open("Classes" + "/Sorted/" + "Alphabetical.txt", "w")
for lettername in string.uppercase:
    try:
        with open('Classes/%s.txt' % lettername) as inp:
            lines = inp.read().splitlines()
    except IOError:
        pass
    else:
        f2.write('%s - score = %s' % (lines[5], lines[6]))
f2.close()