f = open("1.txt", "r", encoding="utf-8") f_new = open("2.txt", "w", encoding="utf-8") find_str = "wangzai" replace_str = "doubi" for line in f: if find_str in line: line = line.replace(find_str, replace_str) f_new = write(line) f.close() f_new.close() os.remove("config.txt") os.rename("config1.txt", "config.txt")