I’m a beginner programmer currently learning Python and I’m programming a game for the first time.
The name and result of the winner is written to an external file and can be read from and displayed in the form of a table.
However, I am getting an error here:
JavaScript
x
3
1
sort = sorted(results, key = itemgetter(0), reverse = True)
2
IndexError: list index out of range
3
This is the whole function for reference:
JavaScript
1
14
14
1
def leadTable():
2
results = []
3
with open('winnerScores.txt', 'r') as file:
4
r = csv.reader(file, delimiter = ',')
5
for row in r:
6
results.append(row)
7
sort = sorted(results, key = itemgetter(0), reverse = True)
8
print(" nnn==================== Leaderboard Table ====================")
9
print(" Scoret Namet")
10
print("____________________________________________________________n")
11
for row in sort:
12
print ("|",row[0]," t " ,row[1]," "*(9-len(row[1]))," ","|")
13
print("____________________________________________________________nnn")
14
How could I fix this?
Advertisement
Answer
Your file has empty lines, which csv.reader
is returning as empty lists. You should skip them when filling in `results.
JavaScript
1
4
1
for row in r:
2
if len(row) >= 2:
3
results.append(row)
4
I used >= 2
because the code that prints the leaderboard requires row[0]
and row[1]
to be filled in.