python - 在 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
解决方案
推荐阅读
- reactjs - 路由发生时如何保持 react-pro-sidebar 子菜单打开?
- azure - Azure FrontDoor:如何设置内部有多个实例的后端池?
- google-apps-script - 计算一列中的更改次数 - Google Script / Sheets
- python - 即使使用假用户代理也无法得到响应
- mysql - 如何在 docker-compose 中添加 phpMyAdmin
- javascript - 带有 React 的 Tesseract.js:可能无法导出受污染的画布
- django - Waypoint.Infinite 不是构造函数
- spring-boot - 使用 SpringBoot 模块创建 EAR 项目
- kivy - 如何将 MDDropdownMenu 放在 KivyMD 中的 MDlist 项目上?
- ruby-on-rails - Rails 6 无法连接到 AWS Elastic Beanstalk 预置的 RDS。Unix 域套接字“/var/run/postgresql/.s.PGSQL.5432”