YAML
YAML是‘另一种标记语言’的缩写(Ain’t Markup Language),YAML不是XML:
- YAML的可读性好。
- YAML和脚本语言的交互性好。
- YAML使用实现语言的数据类型。
- YAML有一个一致的信息模型。
- YAML易于实现。
上面5条也就是XML不足的地方。同时,YAML也有XML的下列优点:
YAML可以基于流来处理;
YAML表达能力强,扩展性好。
总之,YAML试图用一种比XML更敏捷的方式,来完成XML所完成的任务。
PyYAML
安装
字典
1 | ~]# cat test.yml |
2 | --- |
3 | a: 1 |
4 | b: 2 |
5 | c: |
6 | d: 3 |
7 | e: 4 |
8 |
|
9 |
|
10 | import yaml |
11 | with open('test.yml') as f: |
12 | data=yaml.load(f) |
13 | type(data) |
14 | <class 'dict'> |
15 | print(data) |
16 | {'a': 1, 'b': 2, 'c': {'d': 3, 'e': 4}} |
17 |
|
18 | print(yaml.dump(data,default_flow_style=False) |
19 | a: 1 |
20 | b: 2 |
21 | c: |
22 | d: 3 |
23 | e: 4 |
24 |
|
25 | print(yaml.dump(data,default_flow_style=True)) |
26 | {a: 1, b: 2, c: {d: 3, e: 4}} |
列表
1 | ~]# cat test1.yml |
2 | - a |
3 | - b |
4 | - c |
5 |
|
6 | import yaml |
7 | data=yaml.load(open(‘test1.yml’)) |
8 | type(data) |
9 | <class 'list'> |
10 | print(data) |
11 | ['a', 'b', 'c'] |
多级读取
1 | ~]# cat test.yaml |
2 | --- |
3 | a: 1 |
4 | b: 2 |
5 | c: |
6 | d: 3 |
7 | e: 4 |
8 | --- |
9 | a: 2 |
10 | b: d |
11 |
|
12 | import yaml |
13 | data=yaml.load_all(open(test.yml)) |
14 | type(data) |
15 | <class 'generator'> #是一个生成器 |
16 | for i in data: |
17 | print(i) |
18 |
|
19 | {'a': 1, 'b': 2, 'c': {'d': 3, 'e': 4}} |
20 | {'a': 2, 'b': 'd'} |
转换为python类型
1 | >>> yaml.load(""" |
2 | ... none: [~, null] |
3 | ... bool: [true, false, on, off] |
4 | ... int: 42 |
5 | ... float: 3.14159 |
6 | ... list: [LITE, RES_ACID, SUS_DEXT] |
7 | ... dict: {hp: 13, sp: 5} |
8 | ... """) |
9 |
|
10 | {'none': [None, None], 'int': 42, 'float': 3.1415899999999999, |
11 | 'list': ['LITE', 'RES_ACID', 'SUS_DEXT'], 'dict': {'hp': 13, 'sp': 5}, |
12 | 'bool': [True, False, True, False]} |
yaml与类
1 | class test(object): |
2 | def __init__(self,name,age): |
3 | self.name=name |
4 | self.age=age |
5 | def __repr__(self): |
6 | return "%s(name=%r,age=%r)" % (self.__class__.__name__,self.name,self.age) |
7 |
|
8 | print(yaml.dump(test('jusene',25))) |
9 | !!python/object:__main__.test {age: 25, name: jusene} |
10 |
|
11 | yaml.load(‘’‘ |
12 | !!python/object: __main__.test |
13 | name: jusene |
14 | age: 25 |
15 | ''') |
16 | test(name='jusene',age=25) |
多级输出
1 | import yaml |
2 | >>> print(yaml.dump([1,2,3])) |
3 | [1, 2, 3] |
4 |
|
5 | >>> print(yaml.dump([1,2,3],explicit_start=True)) |
6 | --- [1, 2, 3] |
7 |
|
8 | >>> print(yaml.dump_all([1,2,3],explicit_start=True)) |
9 | --- 1 |
10 | --- 2 |
11 | --- 3 |
12 | ... |
13 |
|
14 | >>> |
15 | >>> print(yaml.dump_all({'a':1,'b':[3,4]},explicit_start=True)) |
16 | --- a |
17 | --- b |
18 | ... |
19 |
|
20 | >>> print(yaml.dump({'a':1,'b':[3,4]},explicit_start=True)) |
21 | --- |
22 | a: 1 |
23 | b: [3, 4] |
参考资料: http://pyyaml.org/wiki/PyYAMLDocumentation