mustafa mustafa - 1 year ago 186
YAML Question

How to separate yaml.dump key:value pair by a new line?

I am trying to make yaml dump each key:value pair on a separate line. Is there a native option to do that? I have tried line_break but couldn't get it to work.

Here is a code example:

import yaml

def test_yaml_dump():

obj = {'key0': 1, 'key1': 2}

with open('test.yaml', 'w') as tmpf:
yaml.dump(obj, tmpf, line_break=0)

The output is:

{key0: 1, key1: 2}

I want it to be:

{key0: 1,
key1: 2}

Answer Source

If you add the argument default_flow_style=False to dump then the output will be:

key1: 2
key0: 1

(the so called block style). That is the much more readable way of dumping Python dicts to YAML mappings. In ruamel.yaml this is the default when using ruamel.yaml.round_trip_dump().

import sys
import ruamel.yaml as yaml

obj = dict(key0=1, key1=2)
yaml.round_trip_dump(obj, sys.stdout)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download