Python讀取和存儲yaml文件的方法
YAML 是 "YAML Ain't a Markup Language"(YAML 不是一種標記語言)的遞歸縮寫。在開發(fā)的這種語言時,YAML 的意思其實是:"Yet Another Markup Language"(仍是一種標記語言)。
YAML 的語法和其他高級語言類似,并且可以簡單表達清單、散列表,標量等數(shù)據(jù)形態(tài)。它使用空白符號縮進和大量依賴外觀的特色,特別適合用來表達或編輯數(shù)據(jù)結(jié)構(gòu)、各種配置文件、傾印調(diào)試內(nèi)容、文件大綱(例如:許多電子郵件標題格式和YAML非常接近)。
基本語法
大小寫敏感
使用縮進表示層級關(guān)系
縮進不允許使用tab,只允許空格
縮進的空格數(shù)不重要,只要相同層級的元素左對齊即可
'#'表示注釋
數(shù)據(jù)類型
YAML 支持以下幾種數(shù)據(jù)類型:
對象:鍵值對的集合,又稱為映射(mapping)/ 哈希(hashes) / 字典(dictionary)
數(shù)組:一組按次序排列的值,又稱為序列(sequence) / 列表(list)
純量(scalars):單個的、不可再分的值
關(guān)于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": { "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 = loadData(data="test.yaml") print(yamlData == data)
上述測試用的test.yaml文件如下:
apiVersion: machinelearning.seldon.io/v1alpha2 kind: SeldonDeployment metadata: name: seldon-model spec: name: test-deployment 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: step_two type: MODEL endpoint: type: REST name: step_one type: MODEL name: example replicas: 1
在上述代碼中可以看到我操作的yaml文件后綴都寫的是yaml,其實寫成yml也是可以的。如下所示:
到此這篇關(guān)于Python讀取和存儲yaml文件的方法的文章就介紹到這了,更多相關(guān)Python讀取和存儲yaml文件內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。