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

相关推荐
❀搜不到22 分钟前
isat-sam分割导出掩码图
开发语言·python
Zane199431 分钟前
ClassName() 只是一步?拆开看 __new__ 和 __init__ 各自在干什么
后端·python
曾阿伦40 分钟前
Trae CN Python环境调试debug指南
开发语言·python
渣男教父1 小时前
Python游戏自动化实战案例
python·编程语言
天天爱吃肉82181 小时前
【工程师笔记|新能源整车电控一次过CISPR25/BCI,汽车EMC/EMI落地十大核心设计技巧】
大数据·人工智能·笔记·python·汽车
m0_617493941 小时前
Python 使用 cryptography 实现数据加密与解密
开发语言·python
万山寒2 小时前
python依赖包导出离线安装到没有外网的服务器
服务器·开发语言·python
程序员雷欧2 小时前
LongAdder
开发语言·python
月光船幽幽2 小时前
分层阈值规避归藏协议过度重置
人工智能·python
菜冻鱼2 小时前
Python-sklearn-SVM
开发语言·人工智能·python·机器学习·支持向量机·numpy·sklearn