def updateFile(file,old_str,new_str): file_data = "" with open(file, "r") as f: for line in f: line = line.replace(old_str,new_str) file_data += line with open(file,"w") as f: f.write(file_data) updateFile(r'C:\Users\mage\Desktop\新建文本文档.txt','I am very happy.','but I am unhappy')
修改前,注意,只能修改非中文的内容
修改后
注意:这段代码若file不存在,则会自动创建一个
with open(file,"w") as f:
f.write(file_data)