Raindog
Raindog

Reputation: 13

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

Upvotes: 0

Views: 1349

Answers (1)

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)

Upvotes: 2

Related Questions