Search code examples
pythonruamel.yaml

can columns be kept in ruamel.yaml?


I'm reading a YAML file, manipulating it and dumping it again with ruamel.yaml. I'd like to get it as much human readable as it was before. That requires some tables to be kept in columns.

This is a short example of what I need. I'd like the output to be in columns as in the input.

In [1]: import sys

In [2]: from ruamel.yaml import YAML

In [3]: yaml = YAML()

In [4]: tabs = """
   ...: vals:
   ...:   0: {  0:  1, 1:   2,  2:  3  }
   ...:   1: {  0: 12, 1: 2.3,  2: -1.4}
   ...: """

In [5]: yaml.dump(yaml.load(tabs), sys.stdout)
vals:
  0: {0: 1, 1: 2, 2: 3}
  1: {0: 12, 1: 2.3, 2: -1.4}

Can that be done?


Python code for reference:

import sys
from ruamel.yaml import YAML

yaml = YAML()

tabs = """
vals:
  0: {  0:  1, 1:   2,  2:  3  }
  1: {  0: 12, 1: 2.3,  2: -1.4}
"""

yaml.dump(yaml.load(tabs), sys.stdout)

Solution

  • No, that won't work. Although ruamel.yaml will keep the individual flow/block style, the extra spaces with the flow-style mappings will not be preserved.

    It is not impossible that this will be added at some future date to ruamel.yaml, but currently no such superfluous whitespace information is stored at all except for empty lines between block style.

    BTW You would also have problems with multi-line flow-style mappings with EOL comments.

    If the entries are always mappings shown on one line and themselves values in a mapping, you should be able to do some smart postprocessing (with the transform parameter of the .dump() method, to get the extra spaces in.