首页 > 解决方案 > 在 python 中读取文本文件时,如何解决此列表索引超出范围错误?

问题描述

这是我的代码:

fp = open("todo.txt", "r")

todoContent = fp.readlines()[1:]

for each in todoContent:
    items = each.split(",")
    print("{:} : {:} {:} important and {:} urgent, it {:} been completed".format(
        todoContent.index(each) +1, items[0],
        "is" if items[1] == "Yes" else "is not",
        "is" if items[2] == "Yes" else "is not",
        "has" if items[3] == "Yes" else "has not"))

fp.close()

这是输出:

1 : AB0403 Assignment is important and is not urgent, it has not been completed
2 : Watch Star Wars is not important and is not urgent, it has not been completed
3 : LAMS 4 is important and is urgent, it has not been completed
4 : Buy Grocery is not important and is urgent, it has not been completed
Traceback (most recent call last):
  File "C:/Users/au_yi/PycharmProjects/Python Class AB0403/For testing.py", line 10, in <module>
    "is" if items[1] == "Yes" else "is not",
IndexError: list index out of range

我尝试了几种方法,但似乎无法摆脱错误。我想保持输出原样,只删除错误,所以它看起来像这样:

1 : AB0403 Assignment is important and is not urgent, it has not been completed
2 : Watch Star Wars is not important and is not urgent, it has not been completed
3 : LAMS 4 is important and is urgent, it has not been completed
4 : Buy Grocery is not important and is urgent, it has not been completed

这是txt文件:

Name,Important,Urgent,Complete
AB0403 Assignment,Yes,No,No
Watch Star Wars,No,No,No
LAMS 4,Yes,Yes,Yes
Buy Grocery,No,Yes,No

标签: pythonindex-error

解决方案


推荐阅读