gpt4 book ai didi

python - 如何使用 python 将 yaml 文件作为字典读取并更新值

转载 作者:太空宇宙 更新时间:2023-11-03 14:33:35 24 4
gpt4 key购买 nike

我需要编写函数来读取 YAML 文件并更新特定值。YAML文件是字典,

sample :
test_example:
parent:
attribute_1: 2
attribute_2: 2
parent2:
childList:
- group: 2
type: "test"
track_int:
- key_1: 3
key_2: 25
state: present
state: present
- group: 4
typr: "old"
track_int:
- key_1: 3
key_2: 25
state: present
state: present

现在我需要编写函数来传递 key ,它应该替换特定值的值 ex - 将 test_example["parent2"]["childList"][0]["group"] 更新为 4 并将 test_example["parent"]["attribute_2"] 更新为 5

我怎样才能做到这一点?

最佳答案

如果您想按原样保留输入文件的其余部分,包括 "test""old" 周围多余的引号以及破折号的偏移量在您的序列缩进中,您唯一真正的选择是使用 ruamel.yaml (免责声明:我是该包的作者):

import sys
import ruamel.yaml

yaml = ruamel.yaml.YAML()
yaml.preserve_quotes = True
yaml.indent(mapping=4, sequence=4, offset=2)

with open('input.yaml') as fp:
data = yaml.load(fp)

test_example = data['sample']
test_example["parent2"]["childList"][0]["group"] =4
test_example["parent"]["attribute_2"] = 5
yaml.dump(data, sys.stdout)

给出:

sample:
test_example:
parent:
attribute_1: 2
attribute_2: 5
parent2:
childList:
- group: 4
type: "test"
track_int:
- key_1: 3
key_2: 25
state: present
state: present
- group: 4
typr: "old"
track_int:
- key_1: 3
key_2: 25
state: present
state: present

Python test_example 的命名当然不能与输入文件的 test_example 相对应。它被加载为 None (假设您的输入在呈现 YAML 文档时确实是缩进的)。

关于python - 如何使用 python 将 yaml 文件作为字典读取并更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47114596/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com