pythonpython-3.xyamlpyyamlruamel.yaml

ruamel creating empty blank lines after comment


I'm struggling with doing a roundtrip parsing of a YAML file using ruamel. Below is an example YAML file, input.yaml:

##### Header comment ####
key: #comment1
  key2: val2

Below is the python code

from pathlib import Path
import ruamel.yaml
input = Path("input.yaml")
yaml = ruamel.yaml.YAML()
data = yaml.load(input)
yaml.dump(data,Path("someoutput.yaml"))

This creates an output file with blank newline after each comment

##### Header comment ####

key: #comment1

  key2: val2

I tried recursively going through each comment (ca.comment) and stripping it but was not successful in that

I've gone through multiple questions but the closest I could found was Modifying YAML using ruamel.yaml adds extra new lines. However in this question the comment itself has a newline so not related to my problem

I'm using:

ruamel.yaml==0.17.32
python 3.9
Windows

Solution

  • When handed a pathlib.Path instance as parameter to YAML().load() this file will be opened rb, and the processing of \r\n ending should be done by the scanner.

    It looks like that doesn't work correctly, so I recommend trying:

    data = yaml.load(input.open())
    

    and/or:

    yaml.dump(data,Path("someoutput.yaml").open('w'))