[python] YAML

YAML是一种直观的能够被电脑识别的的数据序列化格式,容易被人类阅读,并且容易和脚本语言交互。YAML类似于XML,但是语法比XML简单得多,对于转化成数组或可以hash的数据时是很简单有效的。YAML基本语法规则如下:

  • 大小写敏感
  • 使用缩进表示层级关系
  • 缩进时不允许使用Tab键,只允许使用空格
  • 缩进的空格数目不重要,只要相同层级的元素左侧对齐即可
  • # 表示注释当前行

YAML 支持的数据结构有三种:

  • 对象:键值对的集合,又称为映射(mapping)/ 哈希(hashes) / 字典(dictionary)
  • 数组:一组按次序排列的值,又称为序列(sequence) / 列表(list)
  • 纯量(scalars):单个的、不可再分的值

对象:对象的一组键值对,使用冒号结构表示。

animal: pets

一组连词线开头的行,构成一个数组

- Cat
- Dog
- Goldfish

对象和数组可以结合使用,形成复合结构。

languages:
 - Ruby
 - Perl
 - Python 
websites:
 YAML: yaml.org 
 Ruby: ruby-lang.org 
 Python: python.org 
 Perl: use.perl.org

字符串默认不使用引号表示。

     str: 这是一行字符串

如果字符串之中包含空格或特殊字符,需要放在引号之中。

    str: '内容: 字符串'


python 使用yaml 

example.ini 文件如下:

house:
  family:
    name: Doe
    parents:
      - John
      - Jane
  address:
    number: 34
    street: Main Street
import yaml
f = open('example.ini',encoding="utf-8")
x = yaml.load(f) #讀取文件,返回一個對象
print(x)
print(x["name"])
print("---------")

aproject = {'name': 'Silenthand Olleander',
            'race': 'Human',
            'traits': ['ONE_HAND', 'ONE_EYE']
            }

ret = yaml.dump(aproject)#将一个python对象生成为yaml文档
print(ret)


aproject = ["a","b","c"]
ret = yaml.dump(aproject)
print(ret)

aproject = ("a","b","c")
ret = yaml.dump(aproject)
print(ret)

aproject = {"a":1,"b":2}
ret = yaml.dump(aproject)
print(ret)

result:

{'house': {'family': {'name': 'Doe', 'parents': ['John', 'Jane']}, 'address': {'number': 34, 'street': 'Main Street'}}}
---------
name: Silenthand Olleander
race: Human
traits: [ONE_HAND, ONE_EYE]

[a, b, c]

[a, b, c]

{a: 1, b: 2}

yaml.dump接收的第二个参数一定要是一个打开的文本文件或二进制文件,yaml.dump会把生成的yaml文档写到文件里

import yaml

aproject = {'name': 'Silenthand Olleander',
            'race': 'Human',
            'traits': ['ONE_HAND', 'ONE_EYE']
            }
f = open(r'E:\AutomaticTest\Test_Framework\config\config.yml','w')
print(yaml.dump(aproject,f))

yaml.dump_all()将多个段输出到一个文件中

import yaml

obj1 = {"name": "James", "age": 20}
obj2 = ["Lily", 19]

with open(r'E:\AutomaticTest\Test_Framework\config\config.yml', 'w') as f:
    yaml.dump_all([obj1, obj2], f)

ref: link

猜你喜欢

转载自blog.csdn.net/lbt_dvshare/article/details/86491328
今日推荐