读取 txt 文件
def read_txt_file(file_path):
"""
读取文本文件的内容
:param file_path: 文本文件的路径
:return: 文件内容
"""
try:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
return content
except FileNotFoundError:
return "文件未找到"
except Exception as e:
return f"读取文件时发生错误: {e}"
text = read_txt_file(file_path)
写入 txt 文件
def save_code_to_txt(code, file_path):
"""
将Python代码保存到文本文件中
:param code: 要保存的Python代码
:param file_path: 保存代码的文件路径
"""
try:
with open(file_path, 'w', encoding='utf-8') as file:
file.write(code)
print(f"代码已成功保存到 {file_path}")
except Exception as e:
print(f"保存代码时发生错误: {e}")
save_code_to_txt(result, file_path)