python之yaml文件解析

pyyaml模块

pip install pyyaml

在安装的时候是pyyaml,但是在使用的时候是yaml.

具体使用

#! /usr/bin/env python
# -*- coding: utf-8 -*-#

# -------------------------------------------------------------------------------
# Name:         tools_01
# Author:       yunhgu
# Date:         2021/6/21 13:40
# Description: 
# -------------------------------------------------------------------------------

import yaml

# fromat the yaml
class MyDumper(yaml.Dumper):
    def increase_indent(self, flow=False, indentless=False):
        return super(MyDumper, self).increase_indent(flow, False)


def parse_yaml(yaml_path):
    with open(yaml_path, 'r', encoding='utf-8') as yaml_file:
        cfg = yaml.load(yaml_file, Loader=yaml.SafeLoader)
        return cfg


def generate_yaml(yaml_file, content_dic):
    with open(yaml_file, 'w', encoding="utf-8") as f:
        yaml.dump(content_dic, f, Dumper=MyDumper, default_flow_style=False, indent=4, allow_unicode=True)


if __name__ == '__main__':
    content = parse_yaml(r"result.yml")
    generate_yaml("a.yaml", content)

posted @ 2021-08-06 16:47  不能说的秘密  阅读(520)  评论(0编辑  收藏  举报