How to write in block style when handling yaml in python Use PyYAML
Suppose you have a yaml file like this
test1: test
test2: test
It can be read in dictionary type as shown below.
>>> import yaml
>>> f = open("test.yml", "r+")
>>> data = yaml.load(f)
>>> data
{'test1': 'test', 'test2': 'test'}
When writing, write with dump ()
as follows.
>>> data
{'test1': 'test', 'test2': 'test'}
>>> f.write(yaml.dump(data))
>>> f.close()
Looking at the written test.yml, it looks like the following, which is not as expected. Very hard to see.
test1: test
test2: test
{test1: test, test2: test}
To write in block style instead of flow style, set default_flow_style = False
atdump ()
.
>>> f.write(yaml.dump(data, default_flow_style=False))
test1: test
test2: test
test1: test
test2: test
It's as expected.
When converting an instance object to yaml with dump ()
, there is a problem that the tag of the instance object is output.
For example, Ordered Dict
that is
How to change the behavior when loading / dumping yaml with PyYAML and its details
.
http://gihyo.jp/dev/serial/01/yaml_library/0003 http://blog.panicblanket.com/archives/1076
Recommended Posts