文件内容替换的核心思路为:
1.以读的模式打开源文件
2.以写的模式创建一个新文件
3.将原文件的内容读出,修改为新内容,写入新文件
4.将原文件删除
5.将新文件重命名为源文件
实现代码
import os
with open('test.txt',encoding='utf-8') as f1,\
open('testbackup.txt',encoding='utf-8',mode='w') as f2:
for i in f1:
new=i.replace('Loto','Sandy')
f2.write(new)
os.remove('test.txt')
os.rename('testbackup.txt','test.txt')