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)

相关推荐
珺毅同学4 小时前
YOLO生成预测json标签迁移问题
python·yolo·json
骑士雄师5 小时前
18.4 长期记忆可修改版
python
~小先生~5 小时前
Python从入门到放弃(一)
开发语言·python
天佑木枫5 小时前
第2天:变量与数据类型 —— 让程序记住信息
python
Dust-Chasing6 小时前
Claude Code源码剖析 - Claude Code 上下文压缩机制
人工智能·python·ai
Cloud_Shy6187 小时前
解读《Effective Python 3rd Edition》:从练气到老魔(第五章 Item 33 - 35)
开发语言·人工智能·笔记·python·学习方法
abcy0712138 小时前
python pandas csv异步后台清洗前端优先返回成功信息
前端·python·pandas
颜酱8 小时前
LangChain使用RAG 入门:让大模型读懂你的私有文档
python·langchain
天天进步20159 小时前
Python全栈项目--校园智能宿舍管理系统
开发语言·python
测试员周周9 小时前
【AI测试智能体-面试】AI测试面试60题(附回答思路)
人工智能·python·功能测试·测试工具·单元测试·自动化·测试用例