Python下解析YAML文件

Python中解析YAML文件主要使用到两个方法,load()和dump()方法,使用方式类似于Python的pickle。熟悉在Python中解析YAML文件,对使用Python做saltstack自定义插件开发时会有很大的帮助

load

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
[root@PolarSnow saltstack]# cat eg.yaml 
name: Tom Smith
age: 37
spouse:
name: Jane Smith
age: 25
children:
- name: Jimmy Smith
age: 15
- name1: Jenny Smith
age1: 12

[root@PolarSnow saltstack]# cat py_yaml.py
#!/usr/bin/env python
#coding=utf-8
import yaml

with open('eg.yaml', 'r') as loadfile:
print yaml.load(loadfile)

[root@PolarSnow saltstack]# python py_yaml.py
{'age': 37, 'spouse': {'age': 25, 'name': 'Jane Smith'}, 'name': 'Tom Smith', 'children': [{'age': 15, 'name': 'Jimmy Smith'}, {'age1': 12, 'name1': 'Jenny Smith'}]}

关键代码

1
2
3
4
5
#!/usr/bin/env python
#coding=utf-8
import yaml
with open('eg.yaml', 'r') as loadfile:
print yaml.load(loadfile)

dump

测试

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
34
35
36
37
38
39
[root@PolarSnow saltstack]# cat eg.yaml 
name: Tom Smith
age: 37
spouse:
name: Jane Smith
age: 25
children:
- name: Jimmy Smith
age: 15
- name1: Jenny Smith
age1: 12

[root@PolarSnow saltstack]# cat py_yaml.py
#!/usr/bin/env python
#coding=utf-8
import yaml
with open('eg.yaml', 'r') as loadfile:
y = yaml.load(loadfile)
print y
with open('eg1.yaml','w') as dumpfile:
dumpfile.write(yaml.dump(y))
print yaml.dump(y)

[root@PolarSnow saltstack]# python py_yaml.py
{'age': 37, 'spouse': {'age': 25, 'name': 'Jane Smith'}, 'name': 'Tom Smith', 'children': [{'age': 15, 'name': 'Jimmy Smith'}, {'age1': 12, 'name1': 'Jenny Smith'}]}
age: 37
children:
- {age: 15, name: Jimmy Smith}
- {age1: 12, name1: Jenny Smith}
name: Tom Smith
spouse: {age: 25, name: Jane Smith}

[root@PolarSnow saltstack]# cat eg1.yaml
age: 37
children:
- {age: 15, name: Jimmy Smith}
- {age1: 12, name1: Jenny Smith}
name: Tom Smith
spouse: {age: 25, name: Jane Smith}

关键代码

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/env python
#coding=utf-8
import yaml

#打开一个yaml文件将其解析,再将解析后的结构再转成yaml写入到新的文件
with open('eg.yaml', 'r') as loadfile:
y = yaml.load(loadfile)
print y

with open('eg1.yaml','w') as dumpfile:
dumpfile.write(yaml.dump(y))
print yaml.dump(y)