gpt4 book ai didi

python - 如何将数据附加到 YAML 文件

转载 作者:太空狗 更新时间:2023-10-30 02:37:56 25 4
gpt4 key购买 nike

我有一个文件*.yaml,内容如下:

bugs_tree:
bug_1:
html_arch: filepath
moved_by: user1
moved_date: '2018-01-30'
sfx_id: '1'

我想在节点 [bugs_tree] 下的这个文件中添加一个新的子元素我已尝试按以下方式执行此操作:

if __name__ == "__main__":
new_yaml_data_dict = {
'bug_2': {
'sfx_id': '2',
'moved_by': 'user2',
'moved_date': '2018-01-30',
'html_arch': 'filepath'
}
}

with open('bugs.yaml','r') as yamlfile:
cur_yaml = yaml.load(yamlfile)
cur_yaml.extend(new_yaml_data_dict)
print(cur_yaml)

然后文件应该是这样的:

bugs_tree:
bug_1:
html_arch: filepath
moved_by: username
moved_date: '2018-01-30'
sfx_id: '1234'
bug_2:
html_arch: filepath
moved_by: user2
moved_date: '2018-01-30'
sfx_id: '2'

当我尝试执行 .append().extend().insert() 时出现错误

cur_yaml.extend(new_yaml_data_dict)
AttributeError: 'dict' object has no attribute 'extend'

最佳答案

如果你想更新文件,读取是不够的。您还需要针对该文件再次写入。这样的事情会起作用:

with open('bugs.yaml','r') as yamlfile:
cur_yaml = yaml.safe_load(yamlfile) # Note the safe_load
cur_yaml['bugs_tree'].update(new_yaml_data_dict)

if cur_yaml:
with open('bugs.yaml','w') as yamlfile:
yaml.safe_dump(cur_yaml, yamlfile) # Also note the safe_dump

我没有对此进行测试,但他的想法是您使用读取读取 文件并写入写入文件。使用 safe_loadsafe_dumpAnthon说:

"There is absolutely no need to use load(), which is documented to be unsafe. Use safe_load() instead"

关于python - 如何将数据附加到 YAML 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48645391/

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