思路
同时打开两个文件,源文件只读模式打开,目标临时文件写模式打开。然后按行读取的同时进行内容替换,并写入目标临时文件。替换完毕后移除源文件,将目标临时文件重命名为源文件。
需求
将测试文件.txt文件中的你好全部替换为hello。
代码实现
import os
with open('测试文件.txt', mode='r', encoding='utf-8') as source, open('tmp.txt', mode='w', encoding='utf-8') as new:
for line in source:
txt = line.replace('你好', 'hello')
new.write(txt)
os.remove('测试文件.txt')
os.rename('tmp.txt', '测试文件.txt')