我有一个文件*.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'
你需要使用update
cur_yaml.update(new_yaml_data_dict)
结果代码
with open('bugs.yaml','r') as yamlfile:
cur_yaml = yaml.load(yamlfile)
cur_yaml.update(new_yaml_data_dict)
print(cur_yaml)
with open('bugs.yaml','w') as yamlfile:
yaml.safe_dump(cur_yaml, yamlfile) # Also note the safe_dump
如果要更新文件,则读取是不够的。您还需要再次写入该文件。像这样的东西会起作用:
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说:
“绝对不需要使用load(),这被记录为不安全。请使用safe_load()代替”
不确定这是否适合每个人的使用案例,但我发现你可以只是...附加到文件,如果它只是拥有一个顶级列表。
这样做的一个动机是它才有意义。另一个是我对每次都必须重新加载和解析整个yaml文件持怀疑态度。我想要做的是使用Django中间件来记录传入的请求,以调试我在开发中加载多个页面时遇到的错误,这对时间要求很高。
如果我必须做OP想要的那些,我会考虑将bug留在他们自己的文件中并从中编写bugs_tree
的内容。
import os
import yaml
def write(new_yaml_data_dict):
if not os.path.isfile("bugs.yaml"):
with open("bugs.yaml", "a") as fo:
fo.write("---\n")
#the leading spaces and indent=4 are key here!
sdump = " " + yaml.dump(
new_yaml_data_dict
,indent=4
)
with open("bugs.yaml", "a") as fo:
fo.write(sdump)
new_yaml_data_dict = {
'bug_1': {
'sfx_id': '1',
'moved_by': 'user2',
'moved_date': '2018-01-20',
'html_arch': 'filepath'
}
}
write(new_yaml_data_dict)
new_yaml_data_dict = {
'bug_2': {
'sfx_id': '2',
'moved_by': 'user2',
'moved_date': '2018-01-30',
'html_arch': 'filepath'
}
}
write(new_yaml_data_dict)
结果
---
bug_1:
html_arch: filepath
moved_by: user2
moved_date: '2018-01-20'
sfx_id: '1'
bug_2:
html_arch: filepath
moved_by: user2
moved_date: '2018-01-30'
sfx_id: '2'