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)

相关推荐
Python×CATIA工业智造8 分钟前
Python迭代协议完全指南:从基础到高并发系统实现
python·pycharm
THMAIL18 分钟前
机器学习从入门到精通 - Transformer颠覆者:BERT与预训练模型实战解析
python·随机森林·机器学习·分类·bootstrap·bert·transformer
0wioiw030 分钟前
Python基础(①⑧Queue)
windows·python
Source.Liu1 小时前
【Python自动化】 21 Pandas Excel 操作完整指南
python·excel·pandas
urhero1 小时前
Python 制作的一个小说在线阅读工具
python·免费·小说·应用软件·小说在线阅读·无广告
跟橙姐学代码1 小时前
列表、元组与字典:Python开发者的三大必备利器,再向高手靠近一步
前端·python·ipython
计算机毕设残哥1 小时前
HDFS存储农业大数据的秘密是什么?高级大豆数据分析与可视化系统架构设计思路
大数据·hadoop·python·hdfs·数据分析·spark·django
蛋仔聊测试1 小时前
pytest源码解析(二)剖析 pytest 的核心组件
python·面试
寒水馨2 小时前
Windows 11 手动下载安装配置 uv、配置国内源
windows·python·国内源·uv·windows11
花花无缺2 小时前
python自动化-pytest-标记
后端·python