Python读取和存储yaml文件的方法
YAML 是 "YAML Ain't a Markup Language"(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:"Yet Another Markup Language"(仍是一种标记语言)。
文章图片
YAML 的语法和其他高级语言类似,并且可以简单表达清单、散列表,标量等数据形态。它使用空白符号缩进和大量依赖外观的特色,特别适合用来表达或编辑数据结构、各种配置文件、倾印调试内容、文件大纲(例如:许多电子邮件标题格式和YAML非常接近)。
基本语法
大小写敏感数据类型
使用缩进表示层级关系
缩进不允许使用tab,只允许空格
缩进的空格数不重要,只要相同层级的元素左对齐即可
'#'表示注释
YAML 支持以下几种数据类型:关于yaml的简单介绍就到这里,今天需要用Python来读取/存储yml文件,废话补多少,直接看具体的操作:
对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)
数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
纯量(scalars):单个的、不可再分的值
#!usr/bin/env python# encoding:utf-8from __future__ import division """__Author__:沂水寒城功能: yaml 操作""" import sysimport yaml def write2Yaml(data, save_path="test.yaml"):"""存储yaml文件"""with open(save_path, "w") as f:yaml.dump(data, f) def loadData(data="https://www.it610.com/article/config.yaml"):"""加载yaml文件"""with open(data, "r") as f:content = f.read()yamlData = https://www.it610.com/article/yaml.load(content)print("yamlData_type: ", type(yamlData))print("yamlData: ", yamlData)return yamlData if __name__ == "__main__":data = https://www.it610.com/article/{"kind": "SeldonDeployment","spec": {"name": "test-deployment","predictors": [{"graph": {"endpoint": {"type": "REST"},"type": "MODEL","name": "step_one","children": {"endpoint": {"type": "REST"},"type": "MODEL","name": "step_two","children": {"endpoint": {"type": "REST"},"type": "MODEL","name": "step_three","children": [],},},},"componentSpecs": [{"spec": {"containers": [{"image": "seldonio/step_one:1.0","name": "step_one",},{"image": "seldonio/step_two:1.0","name": "step_two",},{"image": "seldonio/step_three:1.0","name": "step_three",},]}}],"name": "example","replicas": 1,}],},"apiVersion": "machinelearning.seldon.io/v1alpha2","metadata": {"name": "seldon-model"},} write2Yaml(data, save_path="test.yaml") yamlData = https://www.it610.com/article/loadData(data="test.yaml") print(yamlData =https://www.it610.com/article/= data)
上述测试用的test.yaml文件如下:
apiVersion: machinelearning.seldon.io/v1alpha2kind: SeldonDeploymentmetadata:name: seldon-modelspec:name: test-deploymentpredictors:- componentSpecs:- spec:containers:- image: seldonio/step_one:1.0name: step_one- image: seldonio/step_two:1.0name: step_two- image: seldonio/step_three:1.0name: step_threegraph:children:children:children: []endpoint:type: RESTname: step_threetype: MODELendpoint:type: RESTname: step_twotype: MODELendpoint:type: RESTname: step_onetype: MODELname: examplereplicas: 1
文章图片
在上述代码中可以看到我操作的yaml文件后缀都写的是yaml,其实写成yml也是可以的。如下所示:
文章图片
【Python读取和存储yaml文件的方法】到此这篇关于Python读取和存储yaml文件的方法的文章就介绍到这了,更多相关Python读取和存储yaml文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
推荐阅读
- 急于表达——往往欲速则不达
- 第三节|第三节 快乐和幸福(12)
- 20170612时间和注意力开销记录
- 2.6|2.6 Photoshop操作步骤的撤消和重做 [Ps教程]
- 对称加密和非对称加密的区别
- 眼光要放高远
- 樱花雨
- 前任
- 2020-04-07vue中Axios的封装和API接口的管理
- 烦恼和幸福