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)

相关推荐
淘气的小猴子19 分钟前
Python 魔术方法入门
python
我要见SA姐128 分钟前
DeepSeek Harness 开源贡献手记:从 Issue 到 Merge 的完整旅程
ide·vscode·python·自动化·编辑器
沉下心来学鲁班1 小时前
初识DeepAgents搭建第一个智能体
人工智能·python·langchain
ctlover2 小时前
数据结构:树
数据结构·python
触底反弹3 小时前
🐍 Python 语法全景图:一个 print() 引发的深度探索
python
元Y亨H3 小时前
告别依赖地狱与打包崩溃:Python 项目环境治理与 PyInstaller 避坑实践
python
aramae3 小时前
Python 使用库:标准库与第三方库实战
服务器·开发语言·windows·python
IamZJT_3 小时前
Agent 系统工程 01|模型之外,Harness 到底该负责什么?
人工智能·python·程序员
沧海一笑-dj3 小时前
【Python】Python学习笔记-Python 核心基础
人工智能·python·ai·解释型语言
用户76855341255383 小时前
Python 并发怎么选?一篇讲清 threading、multiprocessing、asyncio 的边界
python