YAML应用
这里主要是记录一下YAML在Python语言中的应用。类比于json库,yaml库与其有惊人的相似之处。一个load方法,一个dump方法。顾名知义,也比较的好理解。
我们先创建一个yaml文件,如下图所示:
存放的数据如下:
name: Tom Smith
age: 37
spouse:
name: Jane Smith
age: 25
children:
- name: Jimmy Smith
age: 15
- name1: Jenny Smith
age1: 12
load用法
import yaml stream = open(‘test_yaml.yaml‘,‘r‘) #读取yaml文件 data = yaml.load(stream) print (data[‘children‘][0][‘name‘] #获取yaml文件中children下面第一个name对应的值
输出结果:
C:\Python34\python3.exe E:/Project_case/demo1.py
Jimmy Smith
理解层面以Python中的dict来理解即可
dump用法
‘‘‘
__author__ = ‘Fighter007‘
__date__ = ‘2018/2/20‘
__Desc__ = YAML 在Python中的应用
‘‘‘
import yaml
s = ‘I have an apple‘
print (yaml.dump(s))
lists = [‘zhangsan‘,‘lisi‘,‘wangwu‘,‘zhaoliu‘]
print (yaml.dump(lists))
class Person(object):
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person(‘zhangsan‘, 19)
p2 = Person(‘lisi‘, 20)
p3 = Person(‘wangwu‘, 21)
persons = [p1, p2, p3]
print (yaml.dump(persons))
输出结果:
I have an apple
...
[zhangsan, lisi, wangwu, zhaoliu]
- !!python/object:__main__.Person {age: 19, name: zhangsan}
- !!python/object:__main__.Person {age: 20, name: lisi}
- !!python/object:__main__.Person {age: 21, name: wangwu}