#!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @Author : liuyuqi @Contact : liuyuqi.gov@msn.cn @Time : 2019/08/11 06:48:32 @Version : 1.0 @License : (C)Copyright 2019 @Desc : 初始化配置文件 ''' import yaml import os # current_path = os.path.dirname(os.path.abspath(__file__)) config_path = os.path.join('..', "conf", 'config.yaml') class YamlConf: ''' yaml配置 ''' @staticmethod def save(data): global config_path try: yaml.dump(data, open(config_path, "w")) except Exception as e: print(e) @staticmethod def load(): global config_path config = {} try: config = yaml.load( open(config_path, "r", encoding="utf-8"), Loader=yaml.SafeLoader) if config is None: config = {} except Exception as e: print(e) return config @staticmethod def set(data_dict): json_obj = YamlConf.load() for key in data_dict: json_obj[key] = data_dict[key] YamlConf.save(json_obj) @staticmethod def get(key, default_val=""): try: result = YamlConf.load()[key] return result except Exception as e: return default_val if __name__ == '__main__': config = {"user": "小舟", "pass": "123", "address": ["shanghai", "beijing"]} print(YamlConf.get("addresss", "default_val")) config2 = {"sex": "girl", "user": "xiaobai"} YamlConf.set(config2)