Как я могу разрешить этот индекс списка вне диапазона ошибок при чтении текстового файла в python? - PullRequest
0 голосов
/ 05 марта 2020

Это мой код:

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

Вот текстовый файл:

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
...