YAML介绍
YAML(YAML Ain’t Markup Language,即YAML不是一种标记语言)是一种高可读的数据序列化的语言,可以被大多数编程语言支持使用,主要用于数据序列化、配置文件等。数据序列化,就是可以高效的表示或描述数据与数据关系的,以便于存储和传输。
基本语法:
- 大小写敏感;
- 使用缩进表示层级关系;
- 缩进不可以使用tab,只能用空格,且空格数不重要,只要相同层级使用空格数即可;
- 用
#
表示注释; - 文件扩展名为yml或yaml;
示例1:表示字典
# 字典
name: "laobai"
result: "success"
示例2:表示列表,一组按序排列的值,数组前加-
符号,符合与值之间需要空格分隔
# 列表
- "laobai"
- "nichengwe"
- "baby2016的天空"
Python操作YAML
安装pyyaml
pyyaml是基于python语言操作yaml的库
$ pip install pyyaml
通过python操作yaml
1、字典:键值对的格式,冒号后面有个空格,每个键值对占一行
# 字典
name: "laobai"
result: "success"
使用python读取yaml的值
import yaml
with open("case01.yaml", mode='r', encoding='utf-8') as f:
r = yaml.safe_load(f)
print(r)
执行代码,
{'name': 'laobai', 'result': 'success'}
读取到一个字典,有2个键值对。
2、列表:一组按序排列的值,数组前加“-”符合,符合与值直接需要空格分隔
# 列表
- "laobai"
- "nichengwe"
- "baby2016的天空"
同样使用上面的程序代码
import yaml
with open("case01.yaml", mode='r', encoding='utf-8') as f:
r = yaml.safe_load(f)
print(r)
执行结果如下:
['laobai', 'nichengwe', 'baby2016的天空']
读取到一个列表,有3个值。
3、字典和列表的相互嵌套使用
a. 字典嵌套字典
# 字典嵌套字典
# 要实现的例子:{person1:{"name":"xiaoguang","age","18"},
# person2:{"name":"xiaoming","age","15"}}
person1:
name: xiaoguang # 最前方有缩进,表示是上一行的子元素
age: 18
person2:
name: xiaoming
age: 15
代码执行结果如下:
{'person1': {'name': 'xiaoguang', 'age': 18}, 'person2': {'name': 'xiaoming', 'age': 15}}
b. 字典嵌套列表
# 字典嵌套列表
# 要实现的例子:{person:['xiaoguang','xiaoming','xiaoding']}
person:
- xiaoguang
- xiaoming
- xiaoding
代码执行结果如下:
{'person': ['xiaoguang', 'xiaoming', 'xiaoding']}
c. 列表嵌套列表
# 列表嵌套列表
# 要实现的例子:[['小光','小明','小顶'],['小峨','小眉']]
-
- '小光'
- '小明'
- '小顶'
-
- '小峨'
- '小眉'
代码执行结果:
[['小光', '小明', '小顶'], ['小峨', '小眉']]
d. 列表嵌套字典
# 列表嵌套字典
# 要实现的例子:[{'username1':'xiaoming'},{'username2':'xiaoguang','password':'123456'}]
-
username1: xiaoming
-
username2: xiaoguang
password: 123456
代码执行结果:
[{'username1': 'xiaoming'}, {'username2': 'xiaoguang', 'password': 123456}]
4、单个文档与多个文档
上面介绍的都是单个文档的情况,但一个yaml文件会同时存储多个文档,多个文档时,用“—”分隔每个文档。
读取单个文档使用yaml.safe_load(),读取多个文档时需要使用yaml.safe_load_all()。
# 多个文档
#{'username1': 'xiaoguang', 'password1': 123456}
#{'username1': 'xiaoming', 'password1': 654321}
---
username1: xiaoguang
password1: 123456
---
username1: xiaoming
password1: 654321
读取多个文档的代码如下:
import yaml
with open("case01.yaml", mode='r', encoding='utf-8') as f:
r = yaml.safe_load_all(f)
for i in r:
print(i)
执行结果:
{'username1': 'xiaoguang', 'password1': 123456}
{'username1': 'xiaoming', 'password1': 654321}
封装读取yaml工具类
import os.path
import yaml
class YamlReader:
# 初始化,判断要读取的文件是否存在
def __init__(self, yamlfile):
if os.path.exists(yamlfile):
self.yamlfile = yamlfile
else:
raise FileNotFoundError("文件不存在")
# 读取单个
def read_data(self):
with open(self.yamlfile, 'rb') as f:
data = yaml.safe_load(f)
return data
# 读取多个
def read_data_all(self):
with open(self.yamlfile, 'rb') as f:
data = list(yaml.safe_load_all(f))
return data