yaml

---   #文档开始,一个文件中支持多个文档
 doe: "a deer, a female deer"
 ray: "a drop of golden sun"
 pi: 3.14159
 xmas: true
 french-hens: 3
 calling-birds:   #数组,单个破折号开始
   - huey
   - dewey
   - louie
   - fred
 xmas-fifth-day:      #字典
   calling-birds: four
   french-hens: 3
   golden-rings: 5
   partridges:         #嵌套字典
     count: 1
     location: "a pear tree"
   turtle-doves: two

在深入研究之前,让我们看看这个文档在 JSON 中的样子。

{
  "doe": "a deer, a female deer",
  "ray": "a drop of golden sun",
  "pi": 3.14159,
  "xmas": true,
  "french-hens": 3,
  "calling-birds": [
     "huey",
     "dewey",
     "louie",
     "fred"
  ],
  "xmas-fifth-day": {
  "calling-birds": "four",
  "french-hens": 3,
  "golden-rings": 5,
  "partridges": {
    "count": 1,
    "location": "a pear tree"
  },
  "turtle-doves": "two"
  }
}

空格是 YAML 格式的一部分。除非另有说明,否则换行符表示字段的结束。您可以使用缩进来构造 YAML 文档。缩进级别可以是一个或多个空格。规范禁止使用制表符,因为工具对它们的处理方式不同。请考虑此文档。里面的项目缩进两个空格。

foo: bar
pleh: help
stuff:
  foo: bar
  bar: foo

让我们看一下一个简单的 Python 脚本如何查看此文档。我们将其保存为名为foo.yaml的文件。PyYAML 包会将 YAML 文件流映射到字典中。我们将遍历最外层的键和值集,并打印键和每个值的字符串表示形式。您可以在此处找到适合您最喜欢的平台的处理器。

Import yaml 

from yaml import load
try:
    from yaml import CLoader as Loader
except ImportError:
    from yaml import Loader

if __name__ == '__main__':

    stream = open("foo.yaml", 'r')
    dictionary = yaml.load(stream)
    for key, value in dictionary.items():
        print (key + " : " + str(value))

The output is:

foo : bar
pleh : help
stuff : {'foo': 'bar', 'bar': 'foo'}

 

posted @ 2024-06-05 11:12  wongchaofan  阅读(2)  评论(0编辑  收藏  举报