如何在Python中向YAML文件添加评论 [英] How can I add a comment to a YAML file in Python

查看:418
本文介绍了如何在Python中向YAML文件添加评论的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 https://pypi.python.org/pypi/ruamel编写YAML文件.yaml

代码如下:

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

在YAML数据之前.

推荐答案

在您的with块中,您可以将所需的任何内容写入文件.由于您只需要在顶部添加评论,因此在调用ruamel之前先添加f.write()呼叫:

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)

这篇关于如何在Python中向YAML文件添加评论的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆