Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Updating a value in a YAML file and dump it

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'}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading