IndexError:列表分配索引超出范围?

问题描述 投票:0回答:1

如何解决此错误?!代码是

from datetime import datetime
with open("1.txt") as f:
    lines = f.readlines()
lines[1] = datetime.today().strftime('%A %d %B %Y at %I:%M %p')
with open("1.txt", "w") as f:
    f.writelines(lines)

错误

  File "test.py", in <module>
    lines[1] = datetime.today().strftime('%A %d %B %Y')
IndexError: list assignment index out of range```
python list indexing variable-assignment
1个回答
0
投票

。txt的内容是什么?假设文件中只有一行,并且您想更新该行,则必须使用第一个索引为[0]的行来进行更新,因此:

lines[0] = datetime.today().strftime('%A %d %B %Y at %I:%M %p')

如果要添加行,则必须使用lines.append(..)


0
投票

您想做什么?我认为您正在尝试将元素添加到列表中。

通过lines[1] = datetime.today().strftime('%A %d %B %Y at %I:%M %p'),您正在更改线的第二个元素。

如果值不存在,您将无法更改,对吗?要在列表末尾添加元素,可以执行lines.append(datetime.today().strftime('%A %d %B %Y at %I:%M %p'))

© www.soinside.com 2019 - 2024. All rights reserved.