
Let's say you have a YAML file named original.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/original.yml", "r") as file:
dictionary = yaml.load(file)
dictionary['food']['grain'] = "rice"
with open("/path/to/new.yml", "w") as file:
yaml.dump(dictionary, file)
Of, if you are feeling brave, you could overwrite the original YAML file with the updated dictionary.
#!/usr/bin/python
import ruamel.yaml
yaml = ruamel.yaml.YAML()
with open("/path/to/original.yml", "r") as file:
dictionary = yaml.load(file)
dictionary['food']['grain'] = "rice"
with open("/path/to/original.yml", "w") as file:
yaml.dump(dictionary, file)
Let's say you YAML file contains a list of items.
foods:
- type: fruit
item: banana
- type: fruit
item: apple
Here is how you could append another item to the YAML list.
#!/usr/bin/python
import ruamel.yaml
yaml = ruamel.yaml.YAML()
with open("/path/to/original.yml", "r") as file:
dictionary = yaml.load(file)
dictionary['foods'].append({'type': 'fruit', 'item': 'grapes' })
with open("/path/to/new.yml", "w") as file:
yaml.dump(dictionary, file)
Be aware that if you have a long value, by default, the value will be wrapped.
#!/usr/bin/python
import ruamel.yaml
yaml = ruamel.yaml.YAML()
with open("/path/to/original.yml", "r") as file:
dictionary = yaml.load(file)
dictionary['foods'].append({'type': 'fruit', 'item': 'asdfasfas dasfasdfasdfdasf adsfasdfafdasf asdfasdfasdfdasf asdfasdfdasfadsfasf asdfasdfdasfasfdas asdfasdfdasfdfas' })
with open("/path/to/new.yml", "w") as file:
yaml.dump(dictionary, file)
In this example, new.yml would have something like this.
foods:
- type: fruit
item: banana
- type: fruit
item: apple
- type: fruit
item: asdfasfas dasfasdfasdfdasf adsfasdfafdasf asdfasdfasdfdasf asdfasdfdasfadsfasf
asdfasdfdasfasfdas asdfasdfdasfdfas
The yaml.width option can be used to set a long enough width to prevent the wrapping.
#!/usr/bin/python
import ruamel.yaml
yaml = ruamel.yaml.YAML()
yaml.width = 1000
with open("/path/to/original.yml", "r") as file:
dictionary = yaml.load(file)
dictionary['foods'].append({'type': 'fruit', 'item': 'asdfasfas dasfasdfasdfdasf adsfasdfafdasf asdfasdfasdfdasf asdfasdfdasfadsfasf asdfasdfdasfasfdas asdfasdfdasfdfas' })
with open("/path/to/new.yml", "w") as file:
yaml.dump(dictionary, file)
Did you find this article helpful?
If so, consider buying me a coffee over at