def alter(file,old_str,new_str): file_data = "" with open(file, "r", encoding="utf-8") as f: for line in f: if old_str in line: line = line.replace(line,new_str) file_data += line with open(file,"w",encoding="utf-8") as f: f.write(file_data) f.close() code_pro = 'mycode' code = f"secret_code = '{code_pro}'" alter("/Users/xc/Desktop/conf.toml", "secret_code", code)