Skip to content Skip to sidebar Skip to footer

How Can I Get Comments From A Yaml File Using Ruamel.yaml In Python?

I'd like to get the comment strings from a YAML file I loaded using ruamel.yaml. The project documentation lacks an API reference and I can't find a relevant example. What's the ri

Solution 1:

The library author comments on this in an issue on BitBucket (May 9, 2016):

The comment preservation has not stabilized, e.g. I need to do something if the key and value of a mapping are not on the same line and the key (or both key and value) have a comment. And my initial target was preservation of existing comments, not so much manipulation.

Through some experimentation I determined the following works for the example code provided in the question above:

print('Comment 1: ' + loaded.ca.comment[1][0].value)
print('Comment 2: ' + loaded.ca.items['a'][2].value)
print('Comment 3: ' + loaded.ca.items['a'][3][0].value)
print('Comment 4: ' + loaded.ca.items['a'][3][1].value)
print('Comment 5: ' + loaded['a'].ca.items['b'][2].value)
print('Comment 6: ' + loaded['a']['c'].ca.items[0][0].value)
print('Comment 7: ' + loaded['a']['c'].ca.items[1][0].value)
print('Comment 8: ' + loaded['a']['c'].ca.end[0].value)
print('Comment 9: ' + loaded['a']['c'].ca.end[1].value)

Post a Comment for "How Can I Get Comments From A Yaml File Using Ruamel.yaml In Python?"