我有一个文件 *.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'
原文由 Qex 发布,翻译遵循 CC BY-SA 4.0 许可协议
如果要更新文件,读取是不够的。您还需要针对该文件再次写入。这样的事情会起作用:
我没有对此进行测试,但他的想法是您使用 读取 来 读取 文件并使用 写入 来 写入 文件。使用
safe_load
和safe_dump
就像 安东 说的那样: