如何将新键和值附加到 yaml 字典文件

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

如何将一对新的键和值附加到 yaml 文件,而不删除文件内容或将整个 yaml 重新添加到它自己?

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

如果我这样做,它会添加新的键和值,但它也会将整个 yaml 文件添加到自身

您需要创建另一个可写缓冲区,可能是这样的:

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)