yaml常见的读取和写入

allow_unicode=True:遇到中文不转换为unicode编码
sort_keys=False:不进行排序,默认按照字母abcd排序

import yaml

def write_yaml_template():
    """
    统一的yaml模板
    :return:
    """
    yaml_template = [{
        'feature': None, 'story': None, 'title': None, 'request': {
            'method': None,
            'url': None,
            'headers': None,
            'params': None,
        },
        'validate': None
    }]
    with open('yaml_template.yaml', 'w', encoding='utf-8') as f:
        yaml.safe_dump(yaml_template, f, allow_unicode=True, sort_keys=False)


def read_yaml_all(path):
    with open(path, 'r', encoding='utf-8') as f:
        value = yaml.safe_load(f)
        return value


def read_yaml_by_key(key):
    """
    根据key读取yaml中的信息
    :return: 
    """
    with open('yaml_template.yaml', 'r', encoding='utf-8') as f:
        value = yaml.safe_load(f)
        assert type(key) == type(value), '数据类型不一致,yaml为列表类型[]'
        return value[key]


def dump_yaml(path, data):
    """
    将字典转写入yaml
    :return: yaml type
    """
    with open(path, 'w', encoding='utf-8') as f:
        yaml.safe_dump(data, f, allow_unicode=True)

你可能感兴趣的:(python,python,yaml)