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

Python 索引器:列表分配索引超出范围?,python,list,indexing,variable-assignment,Python,List,Indexing,Variable Assignment,如何修复此错误?! 代码是 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&g

如何修复此错误?! 代码是

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```
文件“test.py”,位于
行[1]=datetime.today().strftime(“%A%d%B%Y”)
索引器:列表分配索引超出范围```

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

lines[0] = datetime.today().strftime('%A %d %B %Y at %I:%M %p')
如果要添加一行,则必须使用

lines.append(datetime.today().strftime('%A %d %B %Y at %I:%M %p'))

伟大的如果它回答了您的问题,您可以单击答案旁边的灰色复选标记来标记答案。