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

相关推荐
满怀冰雪16 分钟前
25-迁移学习入门:加载预训练模型并微调
人工智能·python·机器学习·迁移学习·paddle
2601_9622845017 分钟前
安卓APP UI自动化测试:Python + UiAutomator2 + pytest + pytest-html
python·pytest·uiautomator2·ui自动化测试·安卓app
2601_9620780329 分钟前
构建RESTful APIs:使用Python和Flask
python·flask·web开发·api设计·构建restfulapis
半亩码田30 分钟前
C#转Python第4.5篇:单元测试:pytest vs xUnit/NUnit
python·单元测试·c#
2601_9623008135 分钟前
Python + Requests + Pytest + Excel + Allure:接口自动化测试项目实战
python·excel·pytest·allure·requests
Zane199438 分钟前
两个线程算两遍循环,为什么只快了一点点不是两倍?GIL连环追问
后端·python
重生之小比特38 分钟前
【Java SE】程序逻辑控制
java·开发语言·python
小灰灰搞电子43 分钟前
Python 函数参数分隔符 *:Keyword-Only Arguments 原理与实践
开发语言·python
2601_962297251 小时前
Authlib 0.13通用Python认证授权库wheel安装包(支持Python 2/3)
python·jwt·oauth2.0·authlib·openidconnect
SamChan901 小时前
大文件多语言PDF翻译性能实测:300页文档的耗时、内存占用与失败率分析
python·ai·pdf·机器翻译