Python Yaml Read and Write File

June 13, 2019
import os
import yaml

YAML_FILE = 'config.yaml'

# optional: create file it doesn't exist
if not os.path.exists(YAML_FILE):
    with open(YAML_FILE, 'w'): pass

# load yaml from file
with open(YAML_FILE, 'r') as f:
    yaml_data = yaml.safe_load(f) or {}

# do something
yaml_data['test'] = ['apple', 'orange', 'pear']

# write yaml to file
with open(YAML_FILE, 'w') as f:
    # yaml.dump(yaml_data, f, default_flow_style=False)
    yaml.safe_dump(yaml_data, f, default_flow_style=False) # , encoding='utf-8', allow_unicode=True
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.