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)

相关推荐
hele_two41 分钟前
快速幂算法
c++·python·算法
l1t1 小时前
利用DeepSeek将python DLX求解数独程序格式化并改成3.x版本
开发语言·python·算法·数独
Cemtery1163 小时前
Day26 常见的降维算法
人工智能·python·算法·机器学习
星空椰4 小时前
快速掌握FastAPI:高效构建Web API
python·fastapi
塔尖尖儿4 小时前
Python中range()到底是什么演示
python
Ethan-D5 小时前
#每日一题19 回溯 + 全排列思想
java·开发语言·python·算法·leetcode
weixin_446934036 小时前
统计学中“in sample test”与“out of sample”有何区别?
人工智能·python·深度学习·机器学习·计算机视觉
weixin_462446236 小时前
使用 Python 测试 Mermaid 与 Graphviz 图表生成(支持中文)
python·mermaid·graphviz
JOBkiller1236 小时前
钢绞线缺陷检测与识别_Cascade-Mask-RCNN_RegNetX模型训练与应用实战
python