Tag Archives: erase

Pyyaml tutorial introduction to pyyaml library and YML writing and reading

PyYAML

Source code: https://github.com/yaml/pyyaml

install

# pip command line installation
pip install PyYAML

# Download the source code for installation
python setup.py install

Import

import yaml

Read yaml file

def read_yaml(yml_file, mode='r', encoding='utf-8'):
    """ Read and convert the contents of yaml to Python objects

    :param yml_file:
    :param mode:
    :param encoding:
    :return:
    """
    # safe_load_all() Open multiple documents
    with open(yml_file, mode=mode, encoding=encoding) as y_file:
        # .load is a non-recommended and unsafe encoding method
        # content = yaml.load(y_file.read(), yaml.FullLoader)
        # .safe_load safe encoding method
        # If you don't trust the input stream, you should use:
        return yaml.safe_load(y_file)

Write yaml file

def write_yaml(yaml_file, data, mode='w', encoding='utf-8', is_flush=True):
    """ Converting Python objects to 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 Solve the problem of writing messy code
        yaml.safe_dump(data, stream=y_file, allow_unicode=True)
        if is_flush:
            y_file.flush()