Pyyaml tutorial introduction to pyyaml library and YML writing and reading


Source code:


# pip command line installation
pip install PyYAML

# Download the source code for installation
python install


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:
    # 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(, 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:
    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:

Read More: