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)

相关推荐
郝学胜-神的一滴6 分钟前
Python数据模型:深入解析及其对Python生态的影响
开发语言·网络·python·程序人生·性能优化
free-elcmacom28 分钟前
机器学习进阶<8>PCA主成分分析
人工智能·python·机器学习·pca
liu****1 小时前
Python 基础语法(二):程序流程控制
开发语言·python·python基础
大连好光景1 小时前
Python打日志
运维·python·运维开发
syt_biancheng1 小时前
博客系统全流程测试总结
python·selenium·测试用例·压力测试·postman
可信计算2 小时前
【算法随想】一种基于“视觉表征图”拓扑变化的NLP序列预测新范式
人工智能·笔记·python·算法·自然语言处理
张广涛2 小时前
【无标题】
python
爱笑的眼睛112 小时前
超越剪枝与量化:下一代AI模型压缩工具的技术演进与实践
java·人工智能·python·ai
yaoh.wang2 小时前
力扣(LeetCode) 14: 最长公共前缀 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
reasonsummer2 小时前
【办公类-18-07】20251215(Python)“口腔检查涂氟信息”批量生成打印(区名、学号、姓名、学校、班级、身份证、户籍、性别、民族)
开发语言·python