Using YAML in python

Page breadcrumbsEnd of page breadcrumbs

YAML stands for “YAML Ain’t Markup Language” and is mostly used in configuration files. YAML, in contrary to JSON, is made to be very readable and is not designed to be used for api’s or other communication protocols. This is because the parsing of a YAML file requires the computer a little bit more effort than parsing a JSON file.

Installing PyYAML

To use YAML in python you have to install the PyYAML module by doing:

pip install PyYAML

Or if you are using pip3:

pip3 install PyYAML

Or when you are on linux (like me):

sudo pip3 install PyYAML

Loading YAML from a file

If you want to parse a YAML file.

# import the yaml module
import yaml
# load the yaml file
document = open('document.yaml', 'r')
# and finally parse the file
parsed = yaml.load(document)
You can simply revert it back to a YAML format by doing:


Loading YAML from a string

This is very similar as loading YAML from a file.

none: [~, null]
bool: [true, false, on, off]
int: 42
float: 3.14159
dict: {hp: 13, sp: 5}