yaml的文件先上
user:
- eric
- wallace
- lily
mail:
- 12312312@qq.com
- 324343@qq.com
mysql:
user: root
password: root
host: localhost
database: testdb
再上代码 :轻轻的封装了一层
import yaml class YamlUtils(object): def __init__(self,filePath): self.fs = open(filePath,encoding="utf-8") def getAllConfigs(self): test_data = yaml.safe_load(self.fs) # 返回的数据像这样: {'user': ['eric', 'wallace', 'lily'], 'mail': ['12312312@qq.com', '324343@qq.com']} return test_data def getSection(self,section): test_data = yaml.safe_load(self.fs) return test_data[section] def writeYaml(self,jsonData): with open("config.yaml", encoding='utf-8', mode='w') as f: try: yaml.dump(data=jsonData, stream=f, allow_unicode=True) except Exception as e: print(e) if __name__ == '__main__': jsonData =response = { "status": 1, "code": "1001", "data": [ { "id": 80, "regname": "toml", "pwd": "QW&@JBK!#&#($*@HLNN", "mobilephone": "13691579846", "leavemount": "0.00", "type": "1", "regtime": "2019-08-14 20:24:45.0" }, { "id": 81, "regname": "toml", "pwd": "QW&@JBK!#&#($*@HLNN", "mobilephone": "13691579846", "leavemount": "0.00", "type": "1", "regtime": "2019-08-14 20:24:45.0" } ], "msg": "获取用户列表成功" } testYaml = YamlUtils("./test.yaml") # ret = testYaml.getAllConfigs() ret = testYaml.getSection("mysql") print(ret)