【问题标题】:IndexError: list assignment index out of range?IndexError:列表分配索引超出范围?
【发布时间】:2020-09-17 23:21:33
【问题描述】:

如何解决这个错误?! 代码是

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】:

    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'))
    

    【讨论】:

    • 太棒了!如果它回答了您的问题,您可以通过单击答案旁边的灰色复选标记来标记答案。
    猜你喜欢
    • 1970-01-01
    • 2020-02-03
    • 2018-10-21
    • 2020-02-13
    • 1970-01-01
    • 2019-03-28
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    相关资源
    最近更新 更多