一. yaml读取和写入的方法
主要用到yaml.safe_load()、yaml.safe_dump()函数进行读写操作。yaml.safe_load()读入的返回是字典,yaml.safe_dump()传入到参数也是字典。
二.具体实现
1.pyaml.py
#!/usr/bin/python3
import os
import logging
from yaml import MarkedYAMLError, safe_load, safe_dump
log = logging.getLogger(__name__)
class YamlLoadError(Exception):
pass
class YamlDumpError(Exception):
pass
class Yaml(object):
def __init__(self, yamlfile):
self.data = self.yaml_load(yamlfile)
def set_value(self, key, value):
if key in self.data:
try:
self.data[key] = value
except Exception as excep:
log.error("Unable to set mata: %s ", excep)
else:
log.error("The key:%s does not exist in the dictionary.", key)
def get_value(self, key):
if key in self.data:
return self.data[key]
else:
log.error("The key:%s does not exist in the dictionary.", key)
def yaml_load(self, yamlfile):
try:
with open(yamlfile,'r') as f:
data = safe_load(f)
log.debug("YAML LOAD: %s", data)
except MarkedYAMLError as e:
log.error("YAML Error: %s", e)
raise YamlLoadError("YAML Error: %s" % str(e))
return data
def yaml_dump(self, yamlfile):
try:
with open(yamlfile, 'w') as f:
safe_dump(self.data, f)
except Exception as e:
log.error("dump to %s error.", yamlfile)
raise YamlDumpError("YAML data dump err %s" % str(e))
2.test_yaml.py
#!/usr/bin/python3
import os
from pyaml import Yaml
if __name__ == "__main__":
yaml = Yaml("test.yml")
yaml.set_value("author","onedog")
yaml.set_value("age","18")
yaml.yaml_dump("./test.yaml")
print("author:%s age:%s ver:%s" %(yaml.get_value('author'), yaml.get_value('age'), yaml.get_value('ver')))
3.test.yml
author: threedog
age: 1
blog: 'www.threedog.cn'
ver: '1.0'
description: 'this is a test yml file'
mail: {email: threedog@tg.cn, name: threedog}
使用python3 test_yaml.py执行完成后,当前目录下生成test.yaml文件,如下:
age: '18'
author: onedog
blog: www.threedog.cn
description: this is a test yml file
mail: {email: threedog@tg.cn, name: threedog}
ver: '1.0'