您似乎误解了代码的作用。我们一行一行地走with open("original.txt", "r+") as file: # open a file for reading
lines = file.readlines() # read the contents into a list of lines
print(lines) # print the whole file
for number, item in enumerate(lines): # iterate over lines
if testStr in item:
i = number +2
print(i) #test
lines.insert(i, newLine) # insert lines into the list
print(lines) #test
break # get out of the look
file.close() # not needed, with statement takes care of closing
您没有修改文件。将文件读入字符串列表并修改列表。要修改实际的文件,您需要打开它进行写入并将列表写回其中。在代码末尾这样做可能会奏效
^{pr2}$