Python YAML Handling (PyYAML)
YAML (YAML Ain't Markup Language) is a human-readable data serialization standard that is often used for configuration files. Python does not have a built-in YAML parser, but PyYAML is a popular third-party library.
Installation
pip install PyYAML
Importing the Module
import yaml
Parsing YAML (Reading)
Use yaml.safe_load() to parse YAML safely. It converts YAML data into Python dictionaries and lists.
From a String
import yaml
yaml_str = """
name: John Doe
age: 30
children:
- name: Jane
age: 10
- name: Bob
age: 5
"""
data = yaml.safe_load(yaml_str)
print(data)
# Output: {'name': 'John Doe', 'age': 30, 'children': [{'name': 'Jane', 'age': 10}, {'name': 'Bob', 'age': 5}]}
From a File
import yaml
with open('config.yaml', 'r') as file:
config = yaml.safe_load(file)
print(config)
Dumping YAML (Emitting)
To convert a Python object into a YAML string, use yaml.dump().
import yaml
data = {
'name': 'John Doe',
'age': 30,
'languages': ['Python', 'JavaScript']
}
yaml_str = yaml.dump(data, sort_keys=False)
print(yaml_str)
Writing to a File
import yaml
data = {'key': 'value'}
with open('output.yaml', 'w') as file:
yaml.dump(data, file)