目录
PYYAML
读取yaml
保存yaml
读取保存的yaml文件
yaml文件规则
yaml文件数据结构
ruamel.yaml
格式化保存yaml
使用ruamel.yaml读取yaml
使用ruamel.yaml时python中符号对应于yaml中符号
config.yaml文件
username: zxx
age: 18
orther:
height: 175CM
weitht: 107KG
JobHistory:
- name: IBM
date: 2015-2017
- name: GA
date: 2017-now
read_yaml.py文件
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# load-yaml.py
import os
import yaml
userInfo = yaml.load(open(r"D:\myproject\MyUtils\test_yaml\config.yaml", 'r'))
print(userInfo)
结果为:
{'JobHistory': [{'name': 'IBM', 'date': '2015-2017'}, {'name': 'GA', 'date': '2017-now'}], 'username': 'zxx', 'orther': {'weitht': '107KG', 'height': '175CM'}, 'age': 18}
import yaml
data = {"cookie1":{'domain': '.yiyao.cc', 'expiry': 1521558688.480118, 'httpOnly': False}}
f = open(r'D:\myproject\MyUtils\test_yaml\save_config.yaml','a')
print(yaml.dump(data, f))
f.close()
结果为
{'cookie1': {'domain': '.yiyao.cc', 'expiry': 1521558688.480118, 'httpOnly': False}}
save_config.yaml文件内容为
import yaml
f = open(r'D:\myproject\MyUtils\test_yaml\save_config.yaml','r')
# 读取文件
cont = f.read()
# 加载数据
x = yaml.load(cont)
# 打印数据
print(x)
f.close()
结果为:
{'cookie1': {'expiry': 1521558688.480118, 'domain': '.yiyao.cc', 'httpOnly': False}}
从上面pyyaml保存yaml的处理中可以发现,保存出来的save_config.yaml是字典形式,不是yaml的标准形式,这对于追求一致性的强迫症来说,有点难受。这时发现有一个库ruamel.yaml可以完美解决这个问题。
from __future__ import print_function
import ruamel.yaml
import os
def generate_yaml_doc_ruamel(yaml_file):
from ruamel import yaml
py_object = {'school': 'zhang',
'students': ['a', 'b']}
file = open(yaml_file, 'w', encoding='utf-8')
yaml.dump(py_object, file, Dumper=yaml.RoundTripDumper)
file.close()
current_path = os.path.abspath(".")
yaml_path = os.path.join(current_path, "save_ruamel_config.yaml")
generate_yaml_doc_ruamel(yaml_path)
结果为
import os
# 通过from ruamel import yaml读取yaml文件
def get_yaml_data_ruamel(yaml_file):
from ruamel import yaml
file = open(yaml_file, 'r', encoding='utf-8')
data = yaml.load(file.read(), Loader=yaml.Loader)
file.close()
print(data)
current_path = os.path.abspath(".")
yaml_path = os.path.join(current_path, "save_ruamel_config.yaml")
get_yaml_data_ruamel(yaml_path)
python中代码
py_object = {'school': 'zhang',
'students': ['a', 'b'],
'age':{'old':34,'young':10},
'test':{'test1':123, 'test2':456, 'test3':{'test3_0':0, 'test3_1':[1,1,1,1]}}}
结果为
age:
young: 10
old: 34
school: zhang
test:
test3:
test3_0: 0
test3_1:
- 1
- 1
- 1
- 1
test2: 456
test1: 123
students:
- a
- b