yaml.load()
from a scalar literal looks like this.
key: |
line 1
line 2
and will get the
{"key": "line1\nline2"}
how to dump the data to a file with the same scalar literal?
yaml.load()
from a scalar literal looks like this.
key: |
line 1
line 2
and will get the
{"key": "line1\nline2"}
how to dump the data to a file with the same scalar literal?
If you install ruamel.yaml
(an enhanced version of PyYAML of which I am the author) from PyPI, you only have to specify the RoundTripParser/Dumper:
import sys
import ruamel.yaml as yaml
yaml_str = """\
# this is the key info
key: |
line 1
line 2
"""
data = yaml.load(yaml_str, Loader=yaml.RoundTripLoader)
yaml.dump(data, sys.stdout, Dumper=yaml.RoundTripDumper)
will give you:
# this is the key info
key: |
line 1
line 2
data
will be a subclass of ordereddict
/OrderedDict
on which the formatting information and the comments are attached, which you can use in
your program in the normal way.