[英]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 ?如何将一对新的键和值附加到 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)
if i do this it adds the new key and value but it also adds the entire yaml file to itself如果我这样做,它会添加新的键和值,但它也会将整个 yaml 文件添加到自身
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.