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)

相关推荐
七夜zippoe6 分钟前
事件驱动架构:构建高并发松耦合系统的Python实战
开发语言·python·架构·eda·事件驱动
Kratzdisteln20 分钟前
【MVCD】PPT提纲汇总
经验分享·python
一个无名的炼丹师1 小时前
GraphRAG深度解析:从原理到实战,重塑RAG检索增强生成的未来
人工智能·python·rag
用户8356290780511 小时前
用Python轻松管理Word页脚:批量处理与多节文档技巧
后端·python
进击的松鼠2 小时前
LangChain 实战 | 快速搭建 Python 开发环境
python·langchain·llm
小北方城市网2 小时前
第1课:架构设计核心认知|从0建立架构思维(架构系列入门课)
大数据·网络·数据结构·python·架构·数据库架构
我的offer在哪里2 小时前
Hugging Face:让大模型触手可及的魔法工厂
人工智能·python·语言模型·开源·ai编程
汤姆yu2 小时前
基于python大数据的协同过滤音乐推荐系统
大数据·开发语言·python
爱学习的小道长2 小时前
Python Emoji库的使用教程
开发语言·python
Data_agent2 小时前
Cssbuy 模式淘宝 / 1688 代购系统南美市场搭建指南
大数据·python