假设我们有一个文件 file.txt,其中包含以下内容:
apple banana orange apple orange
要编辑最后一个实例,我们可以使用以下 Python 代码:
# 打开文件
with open('file.txt', 'r') as file:
# 读取文件所有行
lines = file.readlines()
# 修改最后一个实例为 grape
lines[-1] = 'grape\n'
# 写回文件,覆盖原内容
with open('file.txt', 'w') as file:
file.writelines(lines)
首先使用 with open('file.txt', 'r') as file
打开文件,并使用 readlines()
方法读取所有行,将它们存储在一个列表 lines
中。然后,我们修改 lines
列表中的最后一行,并将其设置为 grape。最后,使用 with open('file.txt', 'w') as file
再次打开文件,并使用 writelines()
方法将 lines
列表中的所有行写回文件中,以覆盖原来的内容。