##此时需要导入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')