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)

相关推荐
苏灿烤鱼2 分钟前
14MB 模型,凭什么跟 270M 对打?
javascript·python·agent
小田学Python9 小时前
100行Python代码,搭一个能干活的AI Agent
python·langchain·大模型·ai agent
Csvn10 小时前
🐍 Day3 : Python 容器精讲 — list、dict、set、tuple 底层实现与高级操作
后端·python
weixin-a1530030831610 小时前
python-装饰器
开发语言·python
我的xiaodoujiao10 小时前
快速学习Python基础知识详细图文教程17--类型注解和断点调试
开发语言·python·学习·测试工具
每天吃饭的羊11 小时前
Chrome DevTools MCP
python
水獭比特13 小时前
localhost 不是安全边界:给 Agent Web 入口补上四层门禁
人工智能·python
Generalzy13 小时前
Whisper + VAD + TTS:一套完整的 Python 本地语音处理流水线
python·whisper·语音识别
qpsj13 小时前
让 LLM 控制 AutoCAD/ZWCAD:COM 自动化 + MCP 封装
python·llm
赟爸13 小时前
直播切片素材杂乱不好复用,易元AI要怎么处理
大数据·人工智能·python