Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSV - list index out of range

I get this error reading CSV file (no headers, 3 columns, 2nd and 3rd strings):

Traceback (most recent call last):
File "C:\Python32\fantasy.py", line 72, in module>
some=row[1]
IndexError: list index out of range*    

Here is part of the code below. It's stupidly simple stuff to be stuck on, but I'm just blank about how it isn't working. I'm new to coding, but have dealt with csv module before and never had problems with this part, and just made some test csv file in notepad to see if it will be read from the same code, and it does. I don't know.

import csv
##############some other code, working good and I believe not relevant to this problem
file=open(r"C:\Users\me\Desktop\file-2.csv","r")
reader=csv.reader(file, delimiter=',', quotechar='"')

for row in reader:
    some=row[1]
like image 733
morris Avatar asked Oct 23 '12 21:10

morris


2 Answers

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]
like image 190
Burhan Khalid Avatar answered Oct 20 '22 17:10

Burhan Khalid


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:

  1. Pass the file through some cleanup script to remove blank lines
  2. change the recognized newline character when you call reader
like image 26
Sheena Avatar answered Oct 20 '22 18:10

Sheena