Python (Scripting) - Append to a YAML file using ruamel.yaml
by
Jeremy Canfield |
Updated: January 31 2024
| Python (Scripting) articles
Let's say you have a YAML file named food.yml that contains the following.
food:
fruit: "apple"
veggy: "pepper"
And you want to modify the file, appending grain: rice. 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 append grain: rice. This uses yaml.load to load the YAML file into a dictionary and then appends grain: rice to the dictionary and then creates a new YAML file containing the updated dictionary.
#!/usr/bin/python
import ruamel.yaml
yaml = ruamel.yaml.YAML()
with open("/path/to/food.yml", "r") as original_file:
dictionary = yaml.load(original_file)
dictionary['food']['grain'] = "rice"
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