I'm trying to parse the comments of a yaml file using ruamel.yaml. The thing is, that I want to parse the comments in some sort of specific (I consider it logic, though) way. I have the following yaml file:
---
# comment for the foo variable
foo: 'foo_val'
# comment for the bar variable
bar: ['item1', 'item2']
And what I have been trying to do is the following:
from ruamel.yaml import YAML
yaml = YAML()
yaml.preserve_quotes = True
yaml.explicit_start = True
stream = open('my_file.yml', 'r')
loaded = yaml.load(stream) # by default is roundtrip
loaded.ca
print(loaded)
what prints the following:
Comment(
start=[None, [CommentToken('# comment for the foo variable\n', line: 1, col: 0)]],
items={
foo: [None, None, CommentToken('\n\n# comment for the bar variable\n', line: 3, col: 0), None]})
ordereddict([('foo', 'foo_val'), ('bar', ['item1', 'item2'])])
As you can see, the commented map (I believe it's called so) does not keep an order. I have tried the other way, commenting below the variable definition but with the Python-style list it doesn't work either.
Does anyone know if it's possible to get the commented map without considering the first comment as that start object? Basically, my expected output will be each variable with the comment just on top, i.e.:
Comment(
items={
foo: [None, None, CommentToken('\n\n# comment for the foo variable\n', line: 0, col: 0), None],
bar: [None, None, CommentToken('\n\n# comment for the bar variable\n', line: 3, col: 0), None],
})
EDIT
Ideally, I need to keep the format like in the example I presented or have a straightforward convertion from one format to another.