【发布时间】:2018-07-16 15:45:02
【问题描述】:
我有一个文件*.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'
【问题讨论】:
-
绝对没有必要使用
load(),它被证明是不安全的。请改用safe_load()。.