Reputation: 43
I am trying to reorganize some data from a csv file using the csv module and when I call row[0]
it gives me this error IndexError: list index out of range
even though it should not be out of the lists range given that I am calling Index 0.
This is a sample of what my data looks like in the csv file. It is only one column.
Caucasian
Black or African American
Caucasian
Asian or Pacific Islander
Caucasian,Hispanic or Latino,Native American or American Indian
Caucasian
Caucasian
Caucasian
Middle Eastern,Asian or Pacific Islander
Asian or Pacific Islander
Heres a sample of my code:
for row in csvReader:
if row[0] == "Hispanic,Latino,or Spanish origin":
print("")
raceList = row[0].split(",")
elif (len(raceList) > 1):
csvWriter.writerow(["Mixed Race"])
elif (row[0] == "African American"):
csvWriter.writerow(["Black or African American"])
Upvotes: 3
Views: 1495
Reputation: 24691
It looks like a row is empty. This produces an empty list when the csvReader
tries to read it, and empty lists don't even have index 0. First thing to do is confirm that this is happening by adding a print statement at the beginning of your for
loop:
print(row)
and after running that, you should see []
printed just before you get the IndexError
.
However, since it's a blank line, we probably don't care about skipping it. To skip the line, just use a continue
statement to jump to the next iteration of the for
loop:
if len(row) == 0: # `if not row:` would also work, but this is somewhat more clear
continue
or handle it differently, depending on what you want to do.
Upvotes: 1