如何修复Python中的IndexError: list assignment index out of range错误?
修复IndexError: list assignment index out of range的问题
这个错误的根源很明确:你试图修改lines列表的第2个元素(索引为1),但你的1.txt文件里的行数不足2行——readlines()返回的列表长度小于2,自然就找不到索引为1的位置了。
举个例子,如果1.txt是空的,lines就是个空列表;如果文件只有1行,lines的长度是1,最大索引只能是0。这时候去访问lines[1],Python就会抛出索引越界的错误。
下面给你两种实用的修复方案,根据你的需求选择:
方案一:确保文件至少有2行,不足则补空行
如果你的业务逻辑要求文件必须有至少2行,不存在的话就用空行填充,可以这么写:
from datetime import datetime with open("1.txt") as f: lines = f.readlines() # 把列表补到至少2行,避免索引越界 while len(lines) < 2: lines.append('\n') # 替换第二行,记得加换行符,不然会和下一行连在一起 lines[1] = datetime.today().strftime('%A %d %B %Y at %I:%M %p') + '\n' with open("1.txt", "w") as f: f.writelines(lines)
方案二:动态插入/替换第二行
如果文件可能是空的或者只有1行,你希望直接在第二行的位置写入内容(存在就替换,不存在就插入),可以用insert方法:
from datetime import datetime with open("1.txt") as f: lines = f.readlines() target_line = datetime.today().strftime('%A %d %B %Y at %I:%M %p') + '\n' if len(lines) >= 2: # 已有第二行,直接替换 lines[1] = target_line else: # 没有第二行,先确保第一行存在(空文件的话先加个空行),再插入 if not lines: lines.append('\n') lines.insert(1, target_line) with open("1.txt", "w") as f: f.writelines(lines)
另外提醒一下:strftime生成的字符串没有换行符,直接赋值的话可能会导致文件格式混乱,所以一定要加上\n哦。
内容的提问来源于stack exchange,提问作者FairBird




