【发布时间】:2021-01-29 15:38:32
【问题描述】:
我不明白为什么这会给我一个“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,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.,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(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] 删除它,但错误仍然存在.. 谢谢你的建议。
【问题讨论】:
标签: python-3.x string for-loop readlines