Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ruamel thinks this list is a multi-document file

This is my valid YAML file:

# my_yaml.yaml
- aaa: zzzzz
  bbbb: 'lksdjflksjdflksdj'
  xxxx:
    qqqq:
      - sldflsdkjflks
  fffff: []

- aaa: zzzzz
  bbbb: 'lksdjflksjdflksdj'
  xxxx:
    qqqq:
      - sldflsdkjflks
  fffff: []

- aaa: zzzzz
  bbbb: 'lksdjflksjdflksdj'
  xxxx:
    qqqq:
      - sldflsdkjflks
  fffff: []

But this is what ruamel.yaml generates:

from ruamel.yaml import YAML

yaml = YAML()
yaml.preserve_quotes = True
yaml.default_flow_style = None
yaml.explicit_start = False
formatted_config = yaml.load(Path("my_yaml.yaml").open().read())
yaml.dump_all(formatted_config, Path("/tmp/derps.yaml"))

/tmp/derps.yaml looks like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

aaa: zzzzz
bbbb: 'lksdjflksjdflksdj'
xxxx:
  qqqq:
  - sldflsdkjflks
fffff: []
---
aaa: zzzzz
bbbb: 'lksdjflksjdflksdj'
xxxx:
  qqqq:
  - sldflsdkjflks
fffff: []
---
aaa: zzzzz
bbbb: 'lksdjflksjdflksdj'
xxxx:
  qqqq:
  - sldflsdkjflks
fffff: []

I don’t understand why it’s inserting --- for each list item. All valid YAML parsers just see this as a list.

How can I make ruamel process this correctly?

>Solution :

Try to use:

from ruamel.yaml import YAML
from pathlib import Path

yaml = YAML()
yaml.preserve_quotes = True
yaml.default_flow_style = None
yaml.explicit_start = False

formatted_config = yaml.load(Path("my_yaml.yaml").open().read())
yaml.dump(formatted_config, Path("/tmp/derps.yaml"))

It’s looks like when dumping a list of mappings, by default, it treats each item in the list as a separate document, hence the — indicators.
The ‘dump’ method should indicate that it should be treated as one document.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading