How can I add a comment to a YAML file in Python
Question: 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.


Answer: 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)
    

