my cheat sheet on PyYAML
1 From pypi.org
"YAML is a data serialization format designed for human readability and
interaction with scripting languages. PyYAML is a YAML parser and emitter
for
Python.
PyYAML features a complete YAML 1.1 parser
, Unicode support, pickle support,
capable extension API, and sensible error messages. PyYAML supports standard
YAML tags and provides Python-specific tags that allow to represent an
arbitrary Python object.
PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistence."
2 Installing
pip install yaml pyyaml
then in a python script:
import yaml
3 PyYAML yaml.load(input) is deprecated
From PyYAML yaml.load deprecated in github for details but summarizing here, the new approach demands the loader be specified, as in:
yaml.load(input, Loader=BaseLoader )
or the equivalent:yaml.base_load(input)
- Current loader choices (there are 4)
- BaseLoader: loads most basic YAML. All scalars are loaded as strings
can also use
yaml.base_load(input)
- SafeLoader: loads subset of YAML language, safely. Recommended for
untrusted input
can also use
yaml.safe_load(input)
- FullLoader: the full YAML language. 5.3.1 still
unsafe
due to someCVEs
can also useyaml.full_load(input)
- UnsafeLoader: also called
Loader
for backward compatibility can also useyaml.unsafe_load(input)
- BaseLoader: loads most basic YAML. All scalars are loaded as strings
can also use
- Alternative syntaxes "sugar" methods:
- yaml.safeload
- yaml.fullload
- yaml.unsafeload
To silence warnings of unsafe load methods,
yaml.warnings({'YAMLLoadWarning': False})
3.1 Writing a python dictionary to a YAML file with dump
The syntax is
with open(r'E:\data\store_file.yaml', 'w') as file: documents = yaml.dump(dict_file, file)
You can also dump in a sorted keys order:
with open(r'E:\data\store_file.yaml') as file: documents = yaml.load(file, Loader=yaml.FullLoader) sort_file = yaml.dump(doc, sort_keys=True) print(sort_file)
3.2 Summarizing: yaml.load and yaml.dump
If you data is safe and trusted, these two are all you need.