0%

python解析YAML

编程免不了要写配置文件,怎么写配置也是一门学问。YAML是专门用来写配置文件的语言,非常简洁和强大,远比JSON格式方便。

一、准备

  1. 安装YAML解析依赖包pip install PyYAML
  2. 准备YAML文件(和test.py同目录),语法自行脑补
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
name: 张翠山
age: 40
son:
- name: 张无忌
age: 20
sex: 男
GF:
- name: 赵敏
age: 20
parent:
mother: 群演
father: 汝阳王
- name: 小昭
age: 20
parent:
mother: 黛绮丝
father: 韩千叶

二、开始

  1. 查看安装的扩展包pip list
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Package           Version
----------------- ----------
astroid 2.3.3
certifi 2019.11.28
chardet 3.0.4
click 7.1.1
idna 2.9
isort 4.3.21
lazy-object-proxy 1.4.3
mccabe 0.6.1
pip 20.0.2
pylint 2.4.4
PyYAML 5.3
requests 2.23.0
setuptools 41.2.0
sh 1.12.14
six 1.14.0
urllib3 1.25.8
wrapt 1.11.2
  1. 代码(test.py)
1
2
3
4
5
6
7
8
9
10
11
12
import os
import yaml

# 获取文件所在目录
base_dir = os.path.dirname(os.path.realpath('__file__'))
# 另一种获取目录的方法
#base_dir = os.getcwd()
#print(base_dir)

file = open(os.path.join(base_dir, 'config.yaml'))
content = yaml.load(file, Loader=yaml.FullLoader)
print(content)
  1. 跑一下代码python3 test.py,结果如下(已格式化)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
{
"name": "张翠山",
"age": 40,
"son":
[
{
"name": "张无忌",
"age": 20,
"sex": "男",
"GF":
[
{
"name": "赵敏",
"age": 20,
"parent":
{
"mother": "群演",
"father": "汝阳王"
}
},
{
"name": "小昭",
"age": 20,
"parent":
{
"mother": "黛绮丝",
"father": "韩千叶"
}
}
]
}
]
}

三、参考

  1. pip
  2. 扩展包
  3. YAML教程
  4. yaml.load