1

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?

Anthon
  • 69,918
  • 32
  • 186
  • 246
jiangwei
  • 36
  • 5
  • ok, I found http://stackoverflow.com/questions/8640959/how-can-i-control-what-scalar-form-pyyaml-uses-for-my-data?rq=1 and http://stackoverflow.com/questions/6432605/any-yaml-libraries-in-python-that-support-dumping-of-long-strings-as-block-liter – jiangwei Feb 15 '16 at 08:29

1 Answers1

0

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.

Anthon
  • 69,918
  • 32
  • 186
  • 246