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)

相关推荐
2601_962078038 分钟前
构建RESTful APIs:使用Python和Flask
python·flask·web开发·api设计·构建restfulapis
半亩码田9 分钟前
C#转Python第4.5篇:单元测试:pytest vs xUnit/NUnit
python·单元测试·c#
2601_9623008114 分钟前
Python + Requests + Pytest + Excel + Allure:接口自动化测试项目实战
python·excel·pytest·allure·requests
Zane199416 分钟前
两个线程算两遍循环,为什么只快了一点点不是两倍?GIL连环追问
后端·python
重生之小比特16 分钟前
【Java SE】程序逻辑控制
java·开发语言·python
小灰灰搞电子21 分钟前
Python 函数参数分隔符 *:Keyword-Only Arguments 原理与实践
开发语言·python
2601_9622972523 分钟前
Authlib 0.13通用Python认证授权库wheel安装包(支持Python 2/3)
python·jwt·oauth2.0·authlib·openidconnect
SamChan9024 分钟前
大文件多语言PDF翻译性能实测:300页文档的耗时、内存占用与失败率分析
python·ai·pdf·机器翻译
GIS数据转换器35 分钟前
遥感GIS一体化技术应用平台
大数据·人工智能·python·安全·数据挖掘
2601_966949651 小时前
批量 K 线不只是提速:因子研究中的数据质量、复权与回测偏差
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash