当前位置: 首页 > 工具软件 > PyYAML > 使用案例 >

【PyYaml】yml教程 pyyaml库介绍及yml写 yml读取

岳奇逸
2023-12-01

Yaml

yaml语言教程

PyYAML

源码: https://github.com/yaml/pyyaml

安装

# pip命令行安装
pip install PyYAML

# 下载源码的安装
python setup.py install

导入

import yaml

读取yaml文件

def read_yaml(yml_file, mode='r', encoding='utf-8'):
    """ yaml中内容读取并转化为Python对象

    :param yml_file:
    :param mode:
    :param encoding:
    :return:
    """
    # safe_load_all() 打开多个文档
    with open(yml_file, mode=mode, encoding=encoding) as y_file:
        # .load 是非推荐的 不安全的编码方式
        # content = yaml.load(y_file.read(), yaml.FullLoader)
        # .safe_load 安全编码方式
        # If you don't trust the input stream, you should use:
        return yaml.safe_load(y_file)

写入yaml文件

def write_yaml(yaml_file, data, mode='w', encoding='utf-8', is_flush=True):
    """ Python对象转换为 yaml

    :param yaml_file:
    :param data:
    :param mode:
    :param encoding:
    :param is_flush:
    :return:
    """
    with open(yaml_file, mode=mode, encoding=encoding) as y_file:
        # yaml.dump(data, stream=y_file)
        # allow_unicode 解决写入乱码的问题
        yaml.safe_dump(data, stream=y_file, allow_unicode=True)
        if is_flush:
            y_file.flush()
 类似资料: