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

How to append new key and value to a yaml dictionary file

How do i append a new pair of key and value to a yaml file, without deleting the file content or re-adding the entire yaml to itself ?

with open(r'D:\Programmi\Linguaggi\Python\testingyaml.yml','r+') as cocktails:
    buffer = yaml.safe_load(cocktails)
    buffer['one'] = 'two'
    yaml.dump(buffer,cocktails)

if i do this it adds the new key and value but it also adds the entire yaml file to itself

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

>Solution :

You need to create another writable buffer, maybe something like this:

with open(r'D:\Programmi\Linguaggi\Python\testingyaml.yml', 'r+') as cocktails:
    buffer = yaml.safe_load(cocktails)
    buffer['one'] = 'two'

with open(r'D:\Programmi\Linguaggi\Python\testingyaml.yml', 'w') as cocktails:
    yaml.dump(buffer, cocktails)
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