Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 right way to access the comments?

import ruamel.yaml

yaml = """\
%YAML 1.2
---
# C1
a: # C2
  # C3
  # C4
  b: 1 # C5
  c: # A comment here will not be parsed properly by ruamel.yaml v0.11.14
  - abc # C6
  - xyz # C7
  # C8
# C9
"""

loaded = ruamel.yaml.round_trip_load(yaml)

# Now what?
like image 371
sourcenouveau Avatar asked Jul 07 '16 18:07

sourcenouveau


People also ask

How do you read a value from a YAML file in Python?

We can read the YAML file using the PyYAML module's yaml. load() function. This function parse and converts a YAML object to a Python dictionary ( dict object). This process is known as Deserializing YAML into a Python.

What is Ruamel Yaml Python?

ruamel.yaml is a YAML parser/emitter that supports roundtrip preservation of comments, seq/map flow style, and map key order For more information about how to use this package see README. Latest version published 8 months ago. License: MPL-2.0. PyPI.

What does YAML dump do?

yaml. dump(data) produces the document as a UTF-8 encoded str object. yaml. dump(data, encoding=('utf-8'|'utf-16-be'|'utf-16-le')) produces a str object in the specified encoding.


1 Answers

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)
like image 120
sourcenouveau Avatar answered Sep 22 '22 02:09

sourcenouveau