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)

相关推荐
smile_Iris9 分钟前
Day 38 GPU训练及类的call方法
开发语言·python
嗷嗷哦润橘_17 分钟前
AI Agent学习:MetaGPT项目之RAG
人工智能·python·学习·算法·deepseek
Smart-Space25 分钟前
tkinter绘制组件(47)——导航边栏
python·tkinter·tinui
ULTRA??40 分钟前
KD-Tree的查询原理
python·算法
电饭叔1 小时前
TypeError:unsupported operand type(s) for -: ‘method‘ and ‘int‘
开发语言·笔记·python
老歌老听老掉牙1 小时前
使用贝叶斯因子量化假设验证所需数据量
python·贝叶斯因子·假设
nix.gnehc1 小时前
poetry 常用命令
python·poetry
一人の梅雨2 小时前
淘宝商品视频接口深度解析:从视频加密解密到多端视频流重构
java·开发语言·python
杼蛘2 小时前
XXL-Job工具使用操作记录
linux·windows·python·jdk·kettle·xxl-job
qq_229058012 小时前
运行djando项目 配置启动类 label_studio包含前后端启动方法
python·django