I have a yaml file that looks like this:
# The following key opens a door
key: value
Is there a way I can load
and dump
this data while maintaining the comment?
If you are using block structured YAML, you can use the python package¹ ruamel.yaml which is a derivative of PyYAML and supports round trip preservation of comments:
import sys
import ruamel.yaml
yaml_str = """\
# example
name:
# details
family: Smith # very common
given: Alice # one of the siblings
"""
yaml = ruamel.yaml.YAML() # defaults to round-trip if no parameters given
code = yaml.load(yaml_str)
code['name']['given'] = 'Bob'
yaml.dump(code, sys.stdout)
with result:
# example
name:
# details
family: Smith # very common
given: Bob # one of the siblings
Note that the end-of-line comments are still aligned.
Instead of normal list
and dict
objects the code
consists of wrapped versions² on which the comments attached.
¹ Install with pip install ruamel.yaml
. Works on Python 2.6/2.7/3.3+
² ordereddict
is used in case of a mapping, to preserve ordering