Home > front end >  ruamel.yaml dump lists without adding new line at the end
ruamel.yaml dump lists without adding new line at the end

Time:10-21

I trying to dump a dict object as YAML using the snippet below:

from ruamel.yaml import YAML
# YAML settings
yaml = YAML(typ="rt")
yaml.default_flow_style = False
yaml.explicit_start = False
yaml.indent(mapping=2, sequence=4, offset=2)

rip= {"rip_routes": ["23.24.10.0/15", "23.30.0.10/15", "50.73.11.0/16", "198.0.0.0/16"]}

file = 'test.yaml'
with open(file, "w") as f:
    yaml.dump(rip, f)

It dumps correctly, but I am getting an new line appended to the end of the list

   rip_routes:
      - 23.24.10.0/15
      - 23.30.0.10/15
      - 198.0.11.0/16

I don't want the new line to be inserted at the end of file. How can I do it?

CodePudding user response:

The newline is part of the representation code for block style sequence elements. And since that code doesn't have much knowledge about context, and certainly not about representing the last element to be dumped in a document, it is almost impossible for the final newline not to be output.

However, the .dump() method has an optional transform parameter that allows you to run the output of the dumped text through some filter:

import sys
import pathlib
import string
import ruamel.yaml

# YAML settings
yaml = ruamel.yaml.YAML(typ="rt")
yaml.default_flow_style = False
yaml.explicit_start = False
yaml.indent(mapping=2, sequence=4, offset=2)

rip= {"rip_routes": ["23.24.10.0/15", "23.30.0.10/15", "50.73.11.0/16", "198.0.0.0/16"]}

def strip_final_newline(s):
    if not s or s[-1] != '\n':
        return s
    return s[:-1]

file = pathlib.Path('test.yaml')
yaml.dump(rip, file, transform=strip_final_newline)

print(repr(file.read_text()))

which gives:

'rip_routes:\n  - 23.24.10.0/15\n  - 23.30.0.10/15\n  - 50.73.11.0/16\n  - 198.0.0.0/16'

It is better to use Path() instances as in the code above, especially if your YAML document is going to contain non-ASCII characters.

  • Related