Python3 Error: list index out of range

萌德咯 2017-07-04 09:58:34


f = open ('userinfo.txt')#flie_ad
lines = f.readlines()
num_f = 0
num_m = 0
for i in lines:
name = i.split(',')[0]
birthday = i.split(',')[1]
print(name,birthday)
if i.split(',')[2] == 'male':
num_m = num_m+1
else:
num_f = num_f +1
print ("There is %d male emp" %num_m)
print ("There is %d emp in this office" %(num_m+num_f))




userinfo.txt

fox,1995,male,
hanmeimei,1990,female,
liming,1989,male,
asdf,1995,female,



执行结果为

fox 1995
hanmeimei 1990
liming 1989
asdf 1995
Traceback (most recent call last):
Flie "test.py", line 14, in <module>
birthday = i.split(',')[1]
IndexError: list index out of range


这个报错无法理解 15行print已经成功输出了 反过头说14行超限了

python版本是3.5.0
系统是Red Hat Enterprise Linux 6
用vim编译
...全文
177 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
sanGuo_uu 2017-07-05
  • 打赏
  • 举报
回复
我的是python2,试了试,能执行。 所以肯定是你的txt文件有问题。 list index out of range——这种报错的原因只有一个,像楼上说的,检查下就好了
# -*- coding:utf-8 -*-

num_f = 0
num_m = 0
f = open ('D:/testP/userinfo.txt')#flie_ad
lines = f.readlines()
f.close()

for line in lines:
	resLine=line.split(',')
	if len(resLine)<3:
		continue
	name = resLine[0]
	birthday = resLine[1]
	print name,birthday
	if resLine[2] == 'male':
		num_m = num_m+1
	else:
		num_f = num_f +1

print "There is %d male emp" %num_m
print "There is %d emp in this office" %(num_m+num_f)
萌德咯 2017-07-05
  • 打赏
  • 举报
回复
引用 1 楼 ckc 的回复:
asdf已经是你数据最后一行了,在后面报的错 说明你的文件里后面还有内容,也许是一个空行 应该在循环里检查一下 if len(i.split(','))<3:break 这样就可以了
做了检查果然通过了 后面检查了一下文档 的确是有一个空行 感谢
ckc 2017-07-05
  • 打赏
  • 举报
回复
asdf已经是你数据最后一行了,在后面报的错 说明你的文件里后面还有内容,也许是一个空行 应该在循环里检查一下 if len(i.split(','))<3:break 这样就可以了

37,720

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧