如何将数据附加到 YAML 文件 [英] How to append data to YAML file
问题描述
我有一个 *.yaml
文件,内容如下:
I have a file *.yaml
with contents as below:
bugs_tree:
bug_1:
html_arch: filepath
moved_by: user1
moved_date: '2018-01-30'
sfx_id: '1'
我想在节点[bugs_tree]
下的这个文件中添加一个新的子元素我试过这样做:
I want to add a new child element to this file under the node [bugs_tree]
I have tried to do this as below:
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)
然后文件应该是这样的:
Then file should looks that:
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()
OR .extend()
OR .insert()
然后得到错误>
When I'm trying to perform .append()
OR .extend()
OR .insert()
then getting error
cur_yaml.extend(new_yaml_data_dict)
AttributeError: 'dict' object has no attribute 'extend'
推荐答案
如果你想更新文件,阅读是不够的.您还需要针对该文件再次写入.像这样的事情会起作用:
If you want to update the file, a read isn't enough. You need to also write again against the file. Something like this would work:
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_load
和 safe_dump
就像 Anthon 说:
I didn't test this, but he idea is that you use a read to read the file and write to write to the file. Use safe_load
and safe_dump
like Anthon said:
绝对没有必要使用 load(),它被证明是不安全的.使用 safe_load() 代替"
"There is absolutely no need to use load(), which is documented to be unsafe. Use safe_load() instead"
这篇关于如何将数据附加到 YAML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!