admin管理员组

文章数量:1405393

I'm having trouble inserting a new line after I've inserted a new node with a Python (3.9.6) script using Ruamel (0.18.10) and need some help.

Here's what I have in my YAML:

node_a: value_a

node_b: value_b

This is what I'm trying to achieve:

node_a: value_a

# Comment
node_c: value_ c

node_b: value_b

Here's what I'm getting:

node_a: value_a

# Comment
node_c: value_ c
node_b: value_b

Here is my code as I iterate through my YAML files:

for key, value in dict.items():
    with open(value["yaml_filepath"], mode='r', newline='', encoding='utf-8') as file:
        data = ru_yaml.load(file) or {}

    if not isinstance(data, ruamel.yamlments.CommentedMap):
        data = ruamel.yamlments.CommentedMap(data)

    data.insert(1, "node_c", value["nodes_value"])
    data.yaml_set_comment_before_after_key("node_c", before="Comment")

I've tried setting the after arg to "\n " for data.yaml_set_comment_before_after_key to create the new line but for some reason the comment doesn't show up when I run the script. I've also added a comment arg to the insert method (also "\n ") and it does work but it automatically creates an EOL "#" assuming it's a comment. I've also tried adding an empty line (data.insert(2, "", comment=None) but it creates a node with no value like so: '':

Anyone know how I can achieve what I'm trying to do? Why doesn't the after arg for yaml_set_comment_before_after_key work as intended, am I misusing it?

本文标签: pythonHow do I insert a new linebreak after a YAML node using RuamelStack Overflow