Python实现复制一个yaml文件内容到另一个yaml文件功能

python 复制代码
def copy_yaml_content(source_file, target_file):
    # 确保源文件存在
    if not os.path.exists(source_file):
        raise FileNotFoundError(f"Source file {source_file} not found.")

        # 读取源文件内容
    with open(source_file, 'r', encoding='utf-8', errors='ignore') as file:
        data = yaml.safe_load(file)

        # 将数据写入目标文件
    with open(target_file, 'w', encoding='utf-8', errors='ignore') as file:
        yaml.dump(data, file, default_flow_style=False)  # default_flow_style=False 保持可读性

source.yaml是你要复制内容的源文件

target.yaml是你要写入的目标文件

yaml.safe_load()函数用于读取YAML文件的内容,并将其解析为Python数据结构(如字典、列表等)。然后,使用yaml.dump()函数将这些数据写回到另一个YAML文件中。

相关推荐
艾斯特_3 小时前
从模型调用到可用聊天应用:会话状态与消息协议
python·ai·aigc
Marst Code3 小时前
Python 3.9 已停止维护!从 3.9 到 3.14 全版本深度对比,生产环境该选哪个?
开发语言·python
llwszx3 小时前
【Java/Go后端手撸原生Agent(第九篇):Plan-and-Execute规划模式——从“走一步看一步“到“先谋后动“】
java·python·golang·agent开发·plan模式·规划执行模式
lxw18449125143 小时前
Python uv 完整使用教程
python·conda·pip·uv
hangyuekejiGEO3 小时前
临沂GEO技术解析与行业应用方案
人工智能·python
不做Java程序猿好多年5 小时前
Java中 String、StringBuffer、StringBuilder 的区别详解
开发语言·python
金銀銅鐵5 小时前
[Python] 用 turtle 来绘制国际象棋棋盘(不含棋子)
python·游戏
這花開嗎5 小时前
2026年TTS文字转语音API哪家强?批量自动化配音成本与技术实测
python·flask·自动化
笨蛋不要掉眼泪5 小时前
Java虚拟机:常用参数
java·开发语言·python
2501_909509105 小时前
DAY 31
python