问题描述
我不明白为什么这会给我一个“IndexError: list index out of range”。 我正在从一个简单的 csv.file 中读取数据,并尝试将值以逗号分隔。
with open('project_twitter_data.csv','r') as twf:
tw = twf.readlines()[1:] # I dont need the very first line
for i in tw:
linelst = i.strip().split(",")
RT = linelst[1]
RP = linelst[2]
rows = "{},{}".format(RT,RP)
我的输出看起来像这样
print(tw) # the original strings.
..\nBORDER Terrier puppy. Name is loving and very protective of the people she loves. Name2 is a 3 year old Maltipoo. Name3 is an 8 year old Corgi.,4,6\nREASON they did not rain but they will reign beautifully couldn't asked for a crime 80 years in the Spring Name's Last Love absolutely love,19,0\nHOME surrounded by snow in my Garden. But City Name people musn't: such a good book: RT @twitteruser The Literature of Conflicted Lands after a,0\n\n"
print (i)
..
BORDER Terrier puppy. Name is loving and very protective of the people she loves. Name2 is a 3 year old Maltipoo. Name3 is an 8 year old Corgi.,6
REASON they did not rain but they will reign beautifully couldn't asked for a crime 80 years in the Spring Name's Last Love absolutely love,0
HOME surrounded by snow in my Garden. But City Name people musn't: such a good book: RT @twitteruser The Literature of Conflicted Lands after a,0
print(linelst)
..
['BORDER Terrier puppy. Name is loving and very protective of the people she loves. Name2 is a 3 year old Maltipoo. Name3 is an 8 year old Corgi.','4','6']
["REASON they did not rain but they will reign beautifully couldn't asked for a crime 80 years in the Spring Name's Last Love absolutely love",'19','0']
["HOME surrounded by snow in my Garden. But City Name people musn't: such a good book: RT @twitteruser The Literature of Conflicted Lands after a",'0','0']
['']
print(rows)
..
4,6
19,0
0,0
# the error
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-7-f27e87689f41> in <module>
6 linelst = i.strip().split(",")
7 # print(linelst)
----> 8 RT = linelst[1]
9 RP = linelst[2]
IndexError: list index out of range
我做错了什么?
我还注意到,在我使用了 strip().split(",") 之后,我的列表的最后出现了一个空列表,[' ']。 我可以用 twf.readlines()[1:][:-1] 删除它但错误仍然存在.. 感谢您的任何建议。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)