python读取写入txt文本文件

读取 txt 文件

python 复制代码
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}"
python 复制代码
# 读取文件内容
text = read_txt_file(file_path)

写入 txt 文件

python 复制代码
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}")
python 复制代码
# 将代码保存到文本文件中
save_code_to_txt(result, file_path)

相关推荐
BoBoZz199 小时前
Hello 隐式建模
python·vtk·图形渲染·图形处理
副露のmagic9 小时前
更弱智的算法学习day 10
python·学习·算法
javpy9 小时前
AI生成 Python小游戏 怪物防御战???
人工智能·python·pygame
爱笑的眼睛119 小时前
超越SIFT与ORB:深入OpenCV特征检测API的设计哲学与高阶实践
java·人工智能·python·ai
中年程序员一枚9 小时前
python开发接口uvicorn方法启动FastAPI,postman调用接口
python·postman·fastapi
周杰伦_Jay9 小时前
【LangGraph】图结构智能体框架核心特性
python·开源
中年程序员一枚10 小时前
让postman调用python的开发接口,链接sqlite数据库,让前后联动起来
数据库·python·postman
爱写Bug的小孙10 小时前
Tools、MCP 和 Function Calling
开发语言·人工智能·python·ai·ai编程·工具调用
rgb2gray10 小时前
城市韧性与交通基础设施系统耦合协调度的时空演变及影响因素
网络·人工智能·python·ai·写作·耦合·耦合协调