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)

相关推荐
哈里谢顿3 分钟前
验证 list() 会调用 `__len__` 方法的深度解析
python·django
vibag35 分钟前
构建智能体与工具调用
python·语言模型·大模型·langgraph
小途软件39 分钟前
高校宿舍访客预约管理平台开发
java·人工智能·pytorch·python·深度学习·语言模型
-dcr1 小时前
49.python自动化
运维·python·自动化
code bean1 小时前
Flask图片服务在不同网络接口下的路径解析问题及解决方案
后端·python·flask
Chasing Aurora1 小时前
Python后端开发之旅(三)
开发语言·python·langchain·protobuf
于越海3 小时前
材料电子理论核心四个基本模型的python编程学习
开发语言·笔记·python·学习·学习方法
中年程序员一枚3 小时前
Springboot报错Template not found For name “java/lang/Object_toString.sql
java·spring boot·python
AI Echoes4 小时前
LangChain 非分割类型的文档转换器使用技巧
人工智能·python·langchain·prompt·agent
程序之巅4 小时前
VS code 远程python代码debug
android·java·python