简体   繁体   English

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

[英]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.

相关问题 如何将 append 键和值(列表)添加到新字典? - How to append key and value (list) to new dictionary? 如何使用函数将新键和值附加到列表字典中 - How to append a new key and value into a dictionary of lists using a function 如何在Python中将新的一组键值对添加到字典中? - How to append a new set of key,value pair to a dictionary in Python? 如何将新键添加到现有字典并将前一个键作为值附加到 for 循环中创建的新键:python - How to add a new key to an existing dictionary and append previous key as value to the new key created in a for loop : python 如何在另一个字典中将字典附加为键的值? - How to append a dictionary as a value of a key in another dictionary? python:如何在yaml文件中添加新密钥和值 - python: how to add a new key and a value in yaml file 如何将新值附加到字典中的列表并将其写入 JSON 文件 - How to append a new value to a list in a dictionary and write it to JSON file 如何将字典列表附加到字典中的键值? - How to append a list of dictionaries to the value of a key in a dictionary? 如何在python字典中的同一个键上附加一个值? - How to append a value on the same key in dictionary of python? 如何将字典的键值附加到列表中 - How to append a key value of dictionary to a list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM