格式化 PyYAML dump() 输出 [英] Formatting PyYAML dump() output

查看:30
本文介绍了格式化 PyYAML dump() 输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字典列表,我想对其进行序列化:

I have a list of dictionaries, which I want to serialize:

list_of_dicts = [ { 'key_1': 'value_a', 'key_2': 'value_b'},
                  { 'key_1': 'value_c', 'key_2': 'value_d'},
                  ...
                  { 'key_1': 'value_x', 'key_2': 'value_y'}  ]

yaml.dump(list_of_dicts, file, default_flow_style = False)

产生以下内容:

- key_1: value_a
  key_2: value_b
- key_1: value_c
  key_2: value_d
(...)
- key_1: value_x
  key_2: value_y

但我想得到这个:

- key_1: value_a
  key_2: value_b
                     <-|
- key_1: value_c       | 
  key_2: value_d       |  empty lines between blocks
(...)                  |
                     <-|
- key_1: value_x
  key_2: value_y

PyYAML documentation 非常简短地讨论了 dump() 参数,但没有似乎没有关于这个特定主题的任何内容.

PyYAML documentation talks about dump() arguments very briefly and doesn't seem to have anything on this particular subject.

手动编辑文件以添加换行符大大提高了可读性,之后结构仍然加载得很好,但我不知道如何让转储方法生成它.

Editing the file manually to add newlines improves readability quite a lot, and the structure still loads just fine afterwards, but I have no idea how to make dump method generate it.

一般来说,除了简单的缩进之外,有没有办法更好地控制输出格式?

And in general, is there a way to have more control over output formatting besides simple indentation?

推荐答案

使用库没有简单的方法来做到这一点(yaml dumper 语法树中的节点对象是被动的,无法发出此信息),所以我结束了与

There's no easy way to do this with the library (Node objects in yaml dumper syntax tree are passive and can't emit this info), so I ended up with

stream = yaml.dump(list_of_dicts, default_flow_style = False)
file.write(stream.replace('\n- ', '\n\n- '))

这篇关于格式化 PyYAML dump() 输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆