python中ruamel.yaml模块是什么?

现在越来越多的开源软件在配置文件中都使用了YAML格式,这种格式文件去除了引号以及各种括号,看起来语法更加精炼。究其原因,YAML格式用更少的语法来表达丰富的含义。YAML是一个可读性更高,用来表达数据序列化的格式。感觉使用上是比json更清晰些的,想要求实的小伙伴可以看下面内容。

ruamel.yaml模块安装:

pipinstallruamel.yaml	

YAML文件的读取

通过代码演示yaml文件的读取

fromruamel.yamlimportYAML
yaml=YAML(typ='safe')
withopen(r'g:\book\code\10\10.1.yml',encoding="utf-8")asfile:
data=yaml.load(file)
print(data)

输出结果:

{'name':'张三','age':22,'sex':'男','interest':{'兴趣1':'爬山','兴趣2':'音乐'},'skill':[{'语言':'JAVA','时间':'2年'},{'语言':'Python','时间':'2年'}],'exam':[{'subject':'英语4级','score':50},{'subject':'高级程序员','score':50}]}

YAML文件的写入

fromruamel.yamlimportYAML
yaml=YAML()
data={'name':'李四','age':22,'sex':'男',
'interest':{'兴趣1':'爬山','兴趣2':'音乐'},
'skill':[{'语言':'Python','时间':'2年'}],
'exam':[{'subject':'高级程序员','score':50}]
}
withopen(r'g:\book\code\10\10.2.yaml',mode='w',encoding="utf-8")asfile:
yaml.dump(data,file)

输出结果:

python中ruamel.yaml模块是什么?

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。