Traceback (most recent call last):IndexError: list index out of range解决方案

文件操作实例:

将日志文件2019-05-17的内容转换成字典样式放在列表中
1,abc,1001,特斯拉
2,bcd,1002,五菱宏光
3,def,1003,摩拜
4,ghj,1004,小黄车

{id:1,name:abc,phone:1001,car:特斯拉}

代码:

lst=[]
with open("2019-05-17", mode="r", encoding="utf-8") as f:
    for line in f:
        dic = {}  # 每行一个字典
        # 1,abc,1001,特斯拉
        ls = line.strip().split(",")  # 逗号切割
        dic['id'] = ls[0]
        dic['name'] = ls[1]
        dic['phone'] = ls[2]
        dic['car'] = ls[3]
        #print(dic)  # strip()去掉空白
        lst.append(dic)

print(lst)

在运行上面代码时,报错:

Traceback (most recent call last):
  File "E:/pycharm file/Python学习之路/知识回顾/文件的各种操作.py", line 138, in
    dic['car'] = ls[3]
IndexError: list index out of range

虽然提示是索引超出范围,其实并没有,最后发现是数据的问题,出现中文的符号,导致不能读出来,索引出错。

你可能感兴趣的:(Python,3,程序报错解决方案)