Nick
Nick

Reputation: 301

IndexError while printing in from csv

While reading in from a CSV file of two columns and 36 Rows long, I reach line 25 and I have an error thrown. I've checked in the file in two different editors and there isn't a newline or anything there. I'm perplexed because the logic seems sound to me.

Linked here is the CSV file.

My traceback (including the last few printed lines) is as follows:

('Line', 23, 'http://arstechnica.com/gadgets/2013/11/samsungs-growth-isnt-in-your-hand-its-in-your-laundry-room/')
('Line', 24, 'http://arstechnica.com/security/2013/11/now-theres-a-bug-bounty-program-for-the-whole-internet/')
Traceback (most recent call last):
  File "getArticleInformation.py", line 69, in <module>
    printCSV()
  File "getArticleInformation.py", line 63, in printCSV
    print ("Line", i, row[1])
IndexError: list index out of range

And the method doing the work in printing the method is as follows:

def printCSV():
    f = csv.reader(open("ArticleLocationCache.csv", "rb"))
    i = 1
    print (i)
    for row in f:
        print ("Line", i, row[1])
        i = i + 1

Any assistance in identifying my error would be amazing. I've been trying to work it out for the last hour.

Upvotes: 2

Views: 82

Answers (1)

PearsonArtPhoto
PearsonArtPhoto

Reputation: 39698

Simply put, you are reading a row that doesn't have at least 2 elements on it. I'm not sure what you want to do with a row that doesn't, I suspect you just want to skip it. Here's an example of how you could do that:

def printCSV():
f = csv.reader(open("ArticleLocationCache.csv", "rb"))
i = 1
print (i)
for row in f:
    if len(row)>=2:
        print ("Line", i, row[1])
        i = i + 1

Looking at your CSV file, it seems like you might not be parsing it correctly. As an alternative to figure out what's going on, try just printing the whole row out, and then figure out why it's not working as you want, as follows:

def printCSV():
f = csv.reader(open("ArticleLocationCache.csv", "rb"))
i = 1
print (i)
for row in f:
    print (row)
    print ("Line", i, row[1])
    i = i + 1

Upvotes: 2

Related Questions