使用Python操作yaml庫第2部
阿新 • • 發佈:2018-02-20
self data zha 技術 span clas __init__ post -s
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}
使用Python操作yaml庫第2部