0
点赞
收藏
分享

微信扫一扫

Vue的学习之数据与方法

和谐幸福的人生 2024-07-24 阅读 6
python

读取 txt 文件

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}"
# 读取文件内容
text = read_txt_file(file_path)

写入 txt 文件

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}")
# 将代码保存到文本文件中
save_code_to_txt(result, file_path)

举报

相关推荐

0 条评论