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

相关推荐
乱写代码18 分钟前
Python开发技巧--类型注解Literal
python
卷无止境25 分钟前
Python FFI 技术深度解析:ctypes、cffi 与 pybind11 的性能差异与实践挑战
后端·python
郝学胜-神的一滴44 分钟前
算法实战:最小k个数——大顶堆的优雅解法
开发语言·数据结构·c++·python·程序人生·算法·排序算法
万笑佛1 小时前
Python 实现Kafka SASL认证生产消费
python
m0_617493943 小时前
Python OpenCV 透视变换(Perspective Transform)详解与实战
开发语言·python·opencv
小李不困还能学3 小时前
PyCharm下载安装与配置教程
ide·python·pycharm
博观而约取厚积而薄发3 小时前
Pytest 从入门到精通,一篇就够(超详细实战教程)
python·测试工具·单元测试·自动化·pytest
imzed3 小时前
使用 Playwright + Pytest 构建 Web UI 自动化测试框架
python·自动化·pytest
普通网友3 小时前
pytest一些常见的插件
开发语言·python·pytest