Reputation: 29
Here is my csv file:
dan, 12pts
Here is the code and I keep getting an index out of range error in my code? I don't understand what's wrong with it:
import csv
with open('scoreboard.csv','r') as csv_file:
csv_reader = csv.reader(csv_file)
for line in csv_reader:
print(line[1])
Can anyone help?
Upvotes: 0
Views: 49
Reputation: 5797
You have a blank line after the first line in your csv file.
Reproducing your error with appending a blank line after your first row (Note: "<" characters are not the part of the csv file):
< dan, 12pts
<
we get the error message of course:
import csv
with open('scoreboard.txt','r') as csv_file:
csv_reader = csv.reader(csv_file)
for line in csv_reader:
print(line[1])
Out:
print(line[1])
IndexError: list index out of range
For first sight the blank line in a csv file can hide pritty well, but after we delete it (or them!):
< dan, 12pts
Out:
12pts
Upvotes: 0
Reputation: 77847
This is quite possibly due to a blank line in your file, such that there is no second element. To diagnose this, instrument your code with a little extra reporting:
import csv
with open('scoreboard.csv','r') as csv_file:
csv_reader = csv.reader(csv_file)
for line in csv_reader:
print(line)
print(len(line))
print(line[1])
This will show you what's going wrong, just before it blows up.
Upvotes: 1