CSV - List Index Out Of Range
Solution 1:
Try checking for blank lines. Also, avoid using file
as a variable name. "r"
is the default mode with open.
import csv
with open(r"C:\Users\me\Desktop\file-2.csv") as f:
reader = csv.reader(f, delimiter=',', quotechar='"')
for row in reader:
if row:
some=row[1]
Solution 2:
It looks like you have an empty line or something. By default each iteration of your for loop grabs a line of text from your csv file. That row of text ends with a newline character. So if you have a blank line then the reader reads it as something like this [].
Do this and you will see what I mean:
for row in reader:
print(repr(row))
some = row[1]
You will find that the last row that gets printed is not of length 2 or more.
There are a few things you can do to fix this:
- Pass the file through some cleanup script to remove blank lines
- change the recognized newline character when you call reader
Solution 3:
This question is old, but I ran into a slightly different solution to this problem so I will put it here for anyone else who might have this problem. My file was so large I could not see the end of it. At the end there was a row with only 2 things in it instead of the typical 5 of my file so when I tried to get the fourth column it was giving me this error. Here was my solution:
for row in reader:
if len(row) > 2:
array.append(row[3])
Solution 4:
I've had this error before as well. My issue was stupid and avoidable though. I copied some code from another program and didn't change the delimiter (in my case from pipe to comma), so of course it was going beyond it's index looking for a pipe when one never existed.
Post a Comment for "CSV - List Index Out Of Range"