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)

相关推荐
odoo中国10 分钟前
Odoo 19 模块结构概述
开发语言·python·module·odoo·核心组件·py文件按
Jelena1577958579212 分钟前
Java爬虫api接口测试
python
踩坑记录1 小时前
leetcode hot100 3.无重复字符的最长子串 medium 滑动窗口(双指针)
python·leetcode
诸神缄默不语3 小时前
Python处理Word文档完全指南:从基础到进阶
python
海棠AI实验室3 小时前
第四章 项目目录结构:src/、configs/、data/、tests/ 的黄金布局
python·项目目录结构
爱笑的眼睛114 小时前
超越可视化:降维算法组件的深度解析与工程实践
java·人工智能·python·ai
清铎4 小时前
leetcode_day12_滑动窗口_《绝境求生》
python·算法·leetcode·动态规划
ai_top_trends5 小时前
2026 年工作计划 PPT 横评:AI 自动生成的优劣分析
人工智能·python·powerpoint
TDengine (老段)5 小时前
TDengine Python 连接器进阶指南
大数据·数据库·python·物联网·时序数据库·tdengine·涛思数据
vyuvyucd5 小时前
深入解析Python asyncio:异步编程核心原理
开发语言·python