python3 对yaml文件的操作

一. 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'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值