# 方式一 文件编辑器用的方式 with open('文件路径', mode='rt', encoding='utf-8') as f: res = f.read() print(res) data = res.replace('华王', '王华') print(data) with open('文件路径',mode='wt',encoding='utf-8') as f1: f1.write(data)
# 用不占内存的方式修改文件 with open('a.txt',mode='rt',encoding='utf-8') as f,\ open('.c.txt.swap',mode = 'wt',encoding='utf-8') as f2: for line in f: f2.write(line.replace('王华','华王')) os.remove('a.txt') os.rename('.c.txt.swap','a,txt')