Python (Scripting) - Modify YAML file ruamel.yaml

by
Jeremy Canfield |
Updated: January 31 2024
| Python (Scripting) articles
Let's say you have a YAML file named that contains the following.
domains:
foo.example.com:
alias: "foo"
region: "us-east-1"
bar.example.com:
alias: "bar"
region: "us-east-1"
And you want to modify the file. This can be done using ruamel.yaml. The pip install command can be used to install the ruamel.yaml package.
pip install ruamel.yaml
And here is how you could create a new file, updating the value of a key.
#!/usr/bin/python
import ruamel.yaml
yaml = ruamel.yaml.YAML()
with open("/path/to/original.yml", "r") as original_file:
dictionary = yaml.load(open("/path/to/original.yml")
dictionary['domains']['foo.example.com']['region'] = 'us-east-2'
dictionary['domains']['bar.example.com']['region'] = 'us-east-2'
with open("/path/to/new.yml", "w") as new_file:
yaml.dump(dictionary, new_file)
Let's say line 1 of the YAML file contains three dashes, which is fairly common with Ansible playbooks.
---
domains:
foo.example.com:
alias: foo
region: us-east-1
bar.example.com:
alias: bar
region: us-east-1
In this scenario, yaml.explicit_start = True will need to be set to include line 1 in yaml.dump.
#!/usr/bin/python
import sys
import ruamel.yaml
yaml = ruamel.yaml.YAML()
yaml.explicit_start = True
with open("/path/to/original.yml", "r") as original_file:
dictionary = yaml.load(open("/path/to/original.yml")
dictionary['domains']['foo.example.com']['region'] = 'us-east-2'
dictionary['domains']['bar.example.com']['region'] = 'us-east-2'
with open("/path/to/new.yml", "w") as new_file:
yaml.dump(dictionary, new_file)
By default, the double quotes around values will often be removed. yaml.preserve_quotes = True can be used to keep the double quotes.
#!/usr/bin/python
import sys
import ruamel.yaml
yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
with open("/path/to/original.yml", "r") as original_file:
dictionary = yaml.load(open("/path/to/original.yml")
dictionary['domains']['foo.example.com']['region'] = 'us-east-2'
dictionary['domains']['bar.example.com']['region'] = 'us-east-2'
with open("/path/to/new.yml", "w") as new_file:
yaml.dump(dictionary, new_file)
Did you find this article helpful?
If so, consider buying me a coffee over at