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)

相关推荐
Jurio.6 分钟前
本机开发 + 多机执行的极简远端运行工具
linux·git·python·github·远程工作
skywalk816314 分钟前
pytest测试的时候这是什么意思?Migrating <class ‘kotti.resources.File‘>
前端·python
overmind16 分钟前
oeasy Python 121[专业选修]列表_多维列表运算_列表相加_列表相乘
java·windows·python
m0_6784854543 分钟前
CSS如何控制表格单元格边框合并_通过border-collapse实现
jvm·数据库·python
m0_748839491 小时前
如何用组合继承模式实现父类方法复用与子类属性独立
jvm·数据库·python
qq_334563551 小时前
PHP源码是否依赖特定芯片组_Intel与AMD平台差异【操作】
jvm·数据库·python
qq_206901392 小时前
如何使用C#调用Oracle存储过程_OracleCommand配置CommandType.StoredProcedure
jvm·数据库·python
m0_748839492 小时前
CSS如何实现元素平滑滚动_使用scroll-behavior属性设置
jvm·数据库·python
Victoria.a2 小时前
python基础语法
开发语言·python
xiaotao1313 小时前
01-编程基础与数学基石: Python核心数据结构完全指南
数据结构·人工智能·windows·python