Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/278.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用ruamel在yaml中插入节点_Python_Pyyaml_Ruamel.yaml - Fatal编程技术网

Python 使用ruamel在yaml中插入节点

Python 使用ruamel在yaml中插入节点,python,pyyaml,ruamel.yaml,Python,Pyyaml,Ruamel.yaml,我想打印以下布局: 额外: 标识符: 生物工具: - http://bio.tools/abyss 我正在使用以下代码添加节点: yaml_文件内容['extra']['identifiers']={} yaml_文件内容['extra']['identifiers']['biotools']=['-http://bio.tools/abyss'] 但是,我得到的是这个输出,它将工具封装在[]中: 额外: 标识符: 生物工具:['-http://bio.tools/abyss'] 我

我想打印以下布局:


额外:
标识符:
生物工具:
- http://bio.tools/abyss

我正在使用以下代码添加节点:


yaml_文件内容['extra']['identifiers']={}
yaml_文件内容['extra']['identifiers']['biotools']=['-http://bio.tools/abyss']

但是,我得到的是这个输出,它将工具封装在[]中:


额外:
标识符:
生物工具:['-http://bio.tools/abyss']


我尝试过其他组合,但没有成功

一旦加载了YAML文件,它就不再是“YAML”;现在它是一个Python数据结构,
biotools
键的内容是一个
列表

>>> import ruamel.yaml as yaml
>>> data = yaml.load(open('data.yml'))
>>> data['extra']['identifiers']['biotools']
['http://bio.tools/abyss']
与任何其他Python列表一样,您可以
向其追加

>>> 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/anothertool

中的破折号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

我已经编辑了我的问题,问题在于输出,即当我想用
换行时,在我的工具名中使用[]http://bio.tools/abyss
@larsksI我不确定您是否完全理解我的答案,但我已经添加了一些进一步的示例来试图澄清问题。
dump()获取了一个意外的关键字参数“default\u flow\u style”
我正在使用来自ruamel.yaml的
导入yaml
和Jinja2的插件
ruamel.yaml.\uu版本
的值是多少?在你的问题中,你能展示你用来加载YAML文档的实际代码吗?谢谢,@Anthon。它工作得非常好。如果这些例子直接涉及到文档来提高图书馆的可用性,那就太好了。如果这个答案解决了你的问题,请考虑点击它来接受它。✔ (勾选)答案旁边。这就是别人知道你的问题已经解决的方式,而不必阅读评论。它还会更改列表中问题和答案的外观。如果出现更好的答案,您可以随时更改已接受的答案。