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文件中。

相关推荐
用户8356290780511 天前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon1 天前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly1 天前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程1 天前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly1 天前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风1 天前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风1 天前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi2 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风2 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风2 天前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python