YAML 是 "YAML Ain't a Markup Language"(YAML 不是一种标记语言)的递归缩写。在开发的这种语言时,YAML 的意思其实是:"Yet Another Markup Language"(仍是一种标记语言)。
YAML 的语法和其他高级语言类似,并且可以简单表达清单、散列表,标量等数据形态。它使用空白符号缩进和大量依赖外观的特色,特别适合用来表达或编辑数据结构、各种配置文件、倾印调试内容、文件大纲(例如:许多电子邮件标题格式和YAML非常接近)。
基本语法
大小写敏感
使用缩进表示层级关系 缩进不允许使用tab,只允许空格 缩进的空格数不重要,只要相同层级的元素左对齐即可 '#'表示注释
数据类型
YAML 支持以下几种数据类型:
对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary) 数组:一组按次序排列的值,又称为序列(sequence) / 列表(list) 纯量(scalars):单个的、不可再分的值
关于yaml的简单介绍就到这里,今天需要用python来读取/存储yml文件,废话补多少,直接看具体的操作:
#!编程客栈usr/bin/env python # encoding:utf-8 from __future__ import division """ __Author__:沂水寒城 功能: yaml 操作 """ import sys import yaml def write2Yaml(data, save_path="test.yaml"): """ 存储yaml文件 """ with open(save_path, "w") as f: yaml.dump(data, f) def loadData(data="config.yaml"): """ 加载yaml文件 """ with open(data, "r") as f: content = f.read() yamlData = yaml.load(content) print("yamlData_type: ", type(yamlData)) print("yamlData: ", yamlData) return yamlData if __name__ == "__main__": data = { "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": { "en编程客栈dpoint": {"type": "REST"}, "type": "MODEL", "name": "step_three", "children": [], }, }, }, "componentSpecs": [ { "spec": { "containers": [ { "image": "seldoni编程客栈o/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 = loadData(data="test.yaml") print(yamlData == data)
上述测试用的test.yaml文件如下:
apiVersion: machinelearning.seldon.io/v1alpha2 kind: SeldonDeployment metadata: name: seldon-model spec: name: test-deploymhttp://www.cppcns.coment predictors: - 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 graph: children: children: children: [] endpoint: type: REST name: step_three type: MODEL endpoint: type: REST name: shttp://www.cppcns.comtep_two type: MODEL endpoint: type: REST name: step_one type: MODEL name: example replicas: 1
在上述代码中可以看到我操作的yaml文件后缀都写的是yaml,其实写成yml也是可以的。如下所示:
到此这篇关于Python读取和存储yaml文件的方法的文章就介绍到这了,更多相关Python读取和存储yaml文件内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
精彩评论