1 importos
2 defalter(file,old_str,new_str):
3 """
4 将替换的字符串写到一个新的文件中,然后将原文件删除,新文件改为原来文件的名字
5 :param file: 文件路径
6 :param old_str: 需要替换的字符串
7 :param new_str: 替换的字符串
8 :return: None
9 """
10 with open(file, "r", encoding="utf-8") as f1,open("%s.bak" % file, "w", encoding="utf-8") as f2:
11 for line inf1:
12 if old_str inline:
13 line =line.replace(old_str, new_str)
14 f2.write(line)
15 os.remove(file)
16 os.rename("%s.bak" %file, file)
17
18 alter("file1", "python", "测试")