为什么当我的代码似乎在范围内时,我会得到一个IndexError:list索引超出范围?

2024-10-01 13:32:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我在编写一个叫做“我的倒计时日历”的项目。我几乎完成了,所以我给了我到目前为止的测试运行。我最后犯了这个错误。 这是我的密码。你知道吗

from tkinter import Tk, Canvas
from datetime import date, datetime

def gete():
    liste = []
    with open('events.txt') as file:
        for line in file:
            line = line.rstrip('\n')
            currente = line.split(',')

            eventd = datetime.strptime(currente[1], '%d/%m/%y').date()
            currente[1] = eventd
            liste.append(currente)
        return liste
def daysbd(date1, date2):
    timeb = str(date1-date2)
    numberofd = timeb.split(' ')
    return numberofd[0]

root = Tk()

c = Canvas(root, width=800, height=800, bg='black')
c.pack()
c.create_text(100, 50, anchor='w', fill='orange', font = 'Arial 28 bold underline', text = 'My Countdown Calendar')


events = gete()
today = date.today()

for event in events:
    eventn = event[0]
    daysu = daysbd(event[1], today)
    display = 'It is %s days until %s ' % (daysu, eventn)
    c.create_text(100, 100, anchor='w', fill='lightblue',\
                  font = 'Arial 28 bold ', text = display)

Tags: textfromimporteventtodaydatetimedatedef
1条回答
网友
1楼 · 发布于 2024-10-01 13:32:04

解析文本文件时,几乎总是希望跳过空行。这里有一个idomatic模式:

for line in file:
    line = line.strip()
    if not line:
        continue
    # process line

如果文件格式依赖于非空行上的空格,则可以将第2行和第3行连接到if not line.strip()。你知道吗

相关问题 更多 >