I have a YAML file, specified as follows:
%YAML 1.2
---
source: 'NULL'
target: 'NULL'
The file is read as a dictionary:
import yaml
with open('path/to/file.yml', 'r+') as file:
value = yaml.safe_load((file))
print(value)
This prints
{'source': 'NULL', 'target': 'NULL'}
Now, just as an example, I have a variable new_v = 23, and I update the value of the source key in the YAML file, how do dump the newly created dict?
>Solution :
You might want to take a look here.
In short, updating a YAML file is the same as writing to any other type of file. Load the file content as a dictionary, update the values as you see fit, then overwrite the entire file, in this case using the dump function from PYYAML to print in YAML format.
import yaml
with open('path/to/file.yml', 'r') as file:
value = yaml.safe_load(file)
value['source'] = 'test'
value['new_v'] = 23
with open('path/to/file.yml', 'w') as file:
file.write(yaml.dump(value))
new_v: 23
source: test
target: 'NULL'
If the order of the keys is relevant to you, consider using an OrderedDict, which keeps the entries in insertion order.