修改'明月'->'太阳'
import os with open(file='诗', mode='r', encoding='utf-8') as f, open(file='诗.bak', mode='w', encoding='utf-8') as f1: for line in f: if '明月' in line: line = line.replace('明月', '太阳') f1.write(line) # os.remove('诗') os.rename('诗.bak', '诗')