Python__替换文件操作

##此时需要导入os模块
import os
with open('old.txt','r',encoding = 'utf-8') as read_f,
open('new.txt','w',encoding = 'utf-8') as write_f:
    for line in read_f:
        if 'mengzhu' in line:
            line.replace('mengzhu','dreamkily')
            write_f.write(line)
        else:
            write_f.write(line)
os.remove('old.txt')
os.rename('new.txt','old.txt')
原文地址:https://www.cnblogs.com/wangmengzhu/p/7163087.html