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)

相关推荐
浩子智控33 分钟前
python程序打包的文件地址处理
开发语言·python·pyqt
Jackey_Song_Odd37 分钟前
Part 1:Python语言核心 - 序列与容器
开发语言·windows·python
m0_662577971 小时前
Python迭代器(Iterator)揭秘:for循环背后的故事
jvm·数据库·python
2501_921649493 小时前
美股历史 K线数据 API接口综合评测与接入指南
后端·python·websocket·金融·restful
小小怪7503 小时前
超越Python:下一步该学什么编程语言?
jvm·数据库·python
Ulyanov3 小时前
基于PyVista的雷达导引头波束三维动态仿真与可视化:从原理到实现的完整指南
python·pyvista·雷达电子战仿真
User_芊芊君子3 小时前
2026最新Python+AI入门指南:从零基础到实战落地,避开90%新手坑
开发语言·人工智能·python
2501_945423543 小时前
数据分析与科学计算
jvm·数据库·python
阿贵---3 小时前
实战:用Python开发一个简单的区块链
jvm·数据库·python