Edit YAML Files in Python (Multiple Examples)
In this tutorial, you’ll learn how to read, modify, and write YAML files in Python using the ruamel.yaml
library.
We’ll start with simple operations like changing scalar values, updating nested structures, manipulating lists, and applying conditional changes.
Change Scalar Value
To change a scalar value in a YAML file, use ruamel.yaml
to load the data, modify the value, and then save it back.
from ruamel.yaml import YAML yaml = YAML() with open('config.yaml', 'r') as file: data = yaml.load(file) data['database']['host'] = '192.168.1.10' # Save the updated YAML file with open('config.yaml', 'w') as file: yaml.dump(data, file)
Output:
Suppose config.yaml
initially contains:
database: host: localhost port: 5432
After running the code, config.yaml
will be:
database: host: 192.168.1.10 port: 5432
Update Nested Value
To update a nested value, such as a key within a nested dictionary, access it directly and assign a new value.
data['server']['credentials']['username'] = 'Amina' data['server']['credentials']['password'] = 'securepassword123' with open('config.yaml', 'w') as file: yaml.dump(data, file)
Output:
If config.yaml
contains:
server: credentials: username: admin password: adminpass
After running the code, it becomes:
server: credentials: username: Amina password: securepassword123
Modify Elements in a List
To modify elements in a list within the YAML data, access the list and change the desired elements.
services = data['services'] services[1] = 'nginx' with open('config.yaml', 'w') as file: yaml.dump(data, file)
Output:
Given config.yaml
has:
services: - apache - mysql - redis
After running the code, config.yaml
changes to:
services: - apache - nginx - redis
Change Values Based on a Condition
To change values based on a condition, loop through the list to find and modify specific entries.
# Update the email of a user named 'Mohamed' for user in data['users']: if user['name'] == 'Mohamed': user['email'] = 'mohamed@example.com' with open('config.yaml', 'w') as file: yaml.dump(data, file)
Output:
If config.yaml
originally contains:
users: - name: Mohamed email: mohamed_old@example.com - name: Sara email: sara@example.com
After executing the code, it updates to:
users: - name: Mohamed email: mohamed@example.com - name: Sara email: sara@example.com
Mokhtar is the founder of LikeGeeks.com. He is a seasoned technologist and accomplished author, with expertise in Linux system administration and Python development. Since 2010, Mokhtar has built an impressive career, transitioning from system administration to Python development in 2015. His work spans large corporations to freelance clients around the globe. Alongside his technical work, Mokhtar has authored some insightful books in his field. Known for his innovative solutions, meticulous attention to detail, and high-quality work, Mokhtar continually seeks new challenges within the dynamic field of technology.