我想印出以下的版面:
extra: identifiers: biotools: - http://bio.tools/abyss
我使用这段代码添加节点:
yaml_file_content['extra']['identifiers'] = {}
yaml_file_content['extra']['identifiers']['biotools'] = ['- http://bio.tools/abyss']
但是,相反,我得到了这个输出,它将工具封装在[]中:
extra: identifiers: biotools: ['- http://bio.tools/abyss']
我试过其他的组合,但没有成功?
发布于 2017-10-13 22:11:54
- http://bio.tools/abyss中的破折号表示序列元素,如果以块样式转储Python,则在输出中添加。
因此,与其做:
yaml_file_content['extra']['identifiers']['biotools'] = ['- http://bio.tools/abyss']你应该做的是:
yaml_file_content['extra']['identifiers']['biotools'] = ['http://bio.tools/abyss']然后使用以下方法强制以块样式输出所有复合元素:
yaml.default_flow_style = False如果希望获得更细粒度的控件,请创建一个ruamel.yaml.comments.CommentedSeq实例:
tmp = ruamel.yaml.comments.CommentedSeq(['http://bio.tools/abyss'])
tmp.fa.set_block_style()
yaml_file_content['extra']['identifiers']['biotools'] = tmp发布于 2017-10-13 20:47:43
一旦加载了YAML文件,它就不再是"yaml";它现在是一个Python结构,biotools键的内容是一个list
>>> import ruamel.yaml as yaml
>>> data = yaml.load(open('data.yml'))
>>> data['extra']['identifiers']['biotools']
['http://bio.tools/abyss']与任何其他Python列表一样,您可以对其进行append:
>>> data['extra']['identifiers']['biotools'].append('http://bio.tools/anothertool')
>>> data['extra']['identifiers']['biotools']
['http://bio.tools/abyss', 'http://bio.tools/anothertool']如果打印出数据结构,则得到有效的YAML:
>>> print( yaml.dump(data))
extra:
identifiers:
biotools: [http://bio.tools/abyss, http://bio.tools/anothertool]当然,如果出于某些原因,您不喜欢列表表示形式,也可以得到语法上等价的内容:
>>> print( yaml.dump(data, default_flow_style=False))
extra:
identifiers:
biotools:
- http://bio.tools/abyss
- http://bio.tools/anothertoolhttps://stackoverflow.com/questions/46737550
复制相似问题