How to use the YAML library in Python
We are going to learn how to use the YAML library in Python. this tutorial on how to work with the YAML format in Python. We use the pyyaml module.
YAML format
YAML (YAML Ain’t Markup Language) is a human-readable data serialization language. YAML natively supports three basic data types: scalars (such as integers, strings, and floats), lists, and associative arrays. YAML is also used in data storage (e.g. debugging output) or transmission (e.g. document headers).
YAML official recommended filename extension for YAML files has been .yaml.
PyYAML
PyYAML is a YAML parser and emitter for Python.
pip install pyyaml
YAML files
#simple.yaml python : 3 django : 4 wordpress : 6 laravel : 4 php : 7 html : 8
#student.yaml name: - Raj - Joi - Die - Emily age: - 16 - 21 - 15 - 19 cities: - Rajkot - Morbi - Mumbai - Surat
Python YAML read
we open the simple.yaml file and load the contents with the yaml.load() method.
#read_yaml.py #!/usr/bin/env python3 import yaml with open('simple.yaml') as val: data = yaml.load(val, Loader=yaml.FullLoader) print(data) Output: {'python': 3, 'django': 4, 'wordpress': 6, 'laravel': 4, 'php': 7, 'html': 8}
Python YAML read documents
we open for the student.yaml file and load the contents with the YAML. load_all() method.
#read_documents.py #!/usr/bin/env python3 import yaml with open('student.yaml') as val: document = yaml.load_all(val, Loader=yaml.FullLoader) for value in document: for key, vals in value.items(): print(key, "==>", vals) Output: name ==> ['Raj', 'Joi', 'Die', 'Emily'] age ==> [16, 21, 15, 19] cities ==> ['Rajkot', 'Morbi', 'Mumbai', 'Surat']
Python YAML dump
Python YAML dump() method serializes a Python object into a YAML stream.
#dump.py #!/usr/bin/env python3 import yaml users_data = [{'name': 'John', 'city': 'Rajkot'}, {'name': 'Emily', 'city': 'Mumbai'}] print(yaml.dump(users_data)) Output: - city: Rajkot name: John - city: Mumbai name: Emily
Python YAML write
We write the data with the dump() method.
#write.py #!/usr/bin/env python3 import yaml users_data = [{'name': 'John', 'city': 'Rajkot'}, {'name': 'Emily', 'city': 'Mumbai'}] with open('data.yaml', 'w') as val: yaml.dump(users_data, val) Output: # data.yaml - city: Rajkot name: John - city: Mumbai name: Emily
Python YAML sorting keys
The example reads data from the items.yaml file and sorts the data by keys in the YAML output.
We can sort keys with the dump’s sort_keys parameter.
#sort_keys.py #!/usr/bin/env python3 import yaml with open('data.yaml') as val: student_data = yaml.load(val, Loader=yaml.FullLoader) print(student_data) sorted_data = yaml.dump(student_data, sort_keys=True) print(sorted_data) Output: [{'city': 'Rajkot', 'name': 'John'}, {'city': 'Mumbai', 'name': 'Emily'}] - city: Rajkot name: John - city: Mumbai name: Emily