I’m using ruamel.yaml 0.18.6
and Python 3.9.x.
I am trying to amend certain objects of data within my yaml file. I load my yaml file, which has a mix of comments and various yaml constructs, add the list entries I need to the Python object(s) of these Yaml data structures and then write them out. However, every time I add a new ‘list’ item, ruamel adds an empty ‘line’ between the last list entry and my new one.
For example, here is an example yaml file:
name: someone
age: 100
# this is a comment
# and another
block1:
- aaa
- bbb
block2:
sub:
- 111
- 222
# a comment
- 333
I’m loading the file with:
from ruamel.yaml import Yaml
def loader(my_yaml_file):
yaml = Yaml()
with open(my_yaml_file, "r", encoding="UTF-8") as file:
return yaml.load(file)
def writer(data, my_yaml_file):
yaml = Yaml()
yaml.indent(mapping=2, seuqence=4, offset=2)
with open(my_yaml_file, "w", encoding="UTF-8") as file:
yaml.dump(data, file)
def do_stuff():
my_yaml_file = "file.yml"
loaded_yaml = loader(my_yaml_file)
loaded_yaml["block1"].append("ccc")
writer(loaded_yaml, my_yaml_file)
When I run my code, my written/updated yaml looks like this:
name: someone
age: 100
# this is a comment
# and another
block1:
- aaa
- bbb
- ccc
block2:
sub:
- 111
- 222
# a comment
- 333
Ideally, I’d like it to look like this:
name: someone
age: 100
# this is a comment
# and another
block1:
- aaa
- bbb
- ccc
block2:
sub:
- 111
- 222
# a comment
- 333
There is always a new line between - bbb
and - ccc
in the block1
module. I can’t figure out why. I’ve tried various settings and suggestions from the documentation but nothing works. It either stays like this, or I can write it out but all the comments vanish. And sadly, I have to keep the comments in the file as they are a requirement.
When I debug, I can see this CommentToken('nn')
mentioned in the ca
section of the module, so it believes that last line is a comment…? Yet on other structures, when it gets written out (such as block2
) it writes it out fine.
Anyone with any suggestions?
6