一、yaml简介
语法:Structure通过空格来展示。Sequence里的项用"-“来代表,Map里的键值对用”:"分隔.
#family.yml
name: Tom Smith
age: 37
spouse:
name: Jane Smith?
age: 25
children:
- name: Jimmy Smith
age: 15
- name1: Jenny Smith
age1: 12
二、python解析
首先需要安装模块
其次,处理内容
>>>import yaml,pprint
>>>f=open('family.yml')#读取文件
>>>res=yaml.load(f)# 导入
>>>f.close()
>>>pprint.pprint(res)#res是一个字典
{'age': 37,
'children': [{'age': 15, 'name': 'Jimmy Smith'},
{'age1': 12, 'name1': 'Jenny Smith'}],
'name': 'Tom Smith',
'spouse': {'age': 25, 'name': 'Jane Smith?'}}
f=open('emp_new.yml','w+')#写入模式打开文件(如不存在,即刻新建)
obj={'sex':'male'}
yaml.dump(obj,f,default_flow_style=False)#将一个python对象生成yaml 文档
f.close()
#emp_new.yml
sex: male
主要的两个函数:
- load(stream, Loader=<class ‘yaml.loader.Loader’>)
Parse the first YAML document in a stream
and produce the corresponding Python object. - dump(data, stream=None, Dumper<class’yaml.dumper.Dumper’>, **kwds)
Serialize a Python object into a YAML stream.
If stream is None, return the produced string instead.
参考:https://www.cnblogs.com/klb561/p/9326677.html