当我的代码出现在范围内时,为什么我得到IndexError:列表索引超出范围?
问题描述:
我正在编写一个名为“我的倒计时日历”的项目。我差不多完成了,所以我给了我迄今为止的测试运行。我最终得到这个错误。 这是我的代码。当我的代码出现在范围内时,为什么我得到IndexError:列表索引超出范围?
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)
答
解析文本文件时,几乎总是希望跳过空行。下面是这个的idomatic模式:
for line in file:
line = line.strip()
if not line:
continue
# process line
如果你的文件格式取决于空白的非空行,你可以加入线2和3 if not line.strip()
。
+0
您的回答非常有帮助和赞赏。 – Osprey
哪条线发生错误? – Barmar
请发布错误代码 – 0TTT0
我的猜测是你的文件中没有''',所以'currente [1]'超出范围。 – Barmar