问题描述
从两列长36行的CSV文件中读取时,我到达第25行,并且抛出错误.我已经在两个不同的编辑器中签入了文件,那里没有换行符或其他任何内容.我很困惑,因为逻辑对我来说似乎很合理.
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.
链接到的是CSV文件.
我的回溯(包括最后几行打印内容)如下:
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.
推荐答案
简而言之,您正在读取的行中至少包含2个元素.我不确定您要对不需要的行做什么,我怀疑您只是想跳过它.这是您如何执行此操作的示例:
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
查看您的CSV文件,似乎您可能无法正确解析它.作为弄清楚正在发生的事情的一种替代方法,请尝试仅打印出整行,然后找出为什么它不能按您的意愿工作,如下所示:
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
这篇关于从csv打印时出现IndexError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!