Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a comment to a YAML file in Python

I am writing a YAML file using https://pypi.python.org/pypi/ruamel.yaml

The code is like this:

import ruamel.yaml
from ruamel.yaml.comments import CommentedSeq

d = {}
for m in ['B1', 'B2', 'B3']:
    d2 = {}
    for f in ['A1', 'A2', 'A3']:
        d2[f] = CommentedSeq(['test', 'test2'])
        if f != 'A2':
            d2[f].fa.set_flow_style()
    d[m] = d2

    with open('test.yml', "w") as f:
        ruamel.yaml.dump(
            d, f, Dumper=ruamel.yaml.RoundTripDumper,
            default_flow_style=False, width=50, indent=8)

I just want to add comment at the top like:

# Data for Class A

Before the YAML data.

like image 822
user3214546 Avatar asked Jun 23 '15 05:06

user3214546


People also ask

How do you comment in YAML?

The shortcut key combination for commenting YAML blocks is Ctrl+Q.

Does YAML support inline comments?

YAML's syntax supports inline comments. Block-level comments, on the other hand, are not supported.

How do you mass comment on YAML?

YAML does not support block or multi-line comments. In order to create a multi-line comment, we need to suffix each line with a # . # block comments.


1 Answers

Within your with block, you can write anything you want to the file. Since you just need a comment at the top, add a call to f.write() before you call ruamel:

with open('test.yml', "w") as f:
    f.write('# Data for Class A\n')
    ruamel.yaml.dump(
        d, f, Dumper=ruamel.yaml.RoundTripDumper,
        default_flow_style=False, width=50, indent=8)
like image 197
dimo414 Avatar answered Sep 22 '22 02:09

dimo414