yaml格式的基础介绍在网上很多,可以参考下面这篇博客
https://www.jianshu.com/p/97222440cd08
总结一下yaml格式主要由3种格式组成 常量 对象 数组,用法见下面的例子
#即表示url属性值;
url: http://www.wolfcode.cn
#即表示server.host属性的值;
server:
host: http://www.wolfcode.cn
#数组,即表示server为[a,b,c]
server:
- 120.168.117.21
- 120.168.117.22
- 120.168.117.23
#常量
pi: 3.14 #定义一个数值3.14
hasChild: true #定义一个boolean值
name: '你好YAML' #定义一个字符串
python中读写yaml存在两个包,自带的PyYAML包和ruamel.yaml包,ruamel.yaml包在PyYAML包上进行了一些改进,下面分别介绍如何使用这两个包
PyYAML的官方APi文档[https://pyyaml.org/wiki/PyYAMLDocumentation]
其中最常用的几个API如下
yaml.load("""
... - Hesperiidae
... - Papilionidae
... - Apatelodidae
... - Epiplemidae
... """)
['Hesperiidae', 'Papilionidae', 'Apatelodidae', 'Epiplemidae']
with open(r'test.yaml', 'r') as f:
yaml.load(f)
yaml.load 可以解析字符串中的或者一个字符流对象中的yaml格式,把yaml中的数组解析成python的列表,常量和对象解析成python的字典,并支持嵌套的字典和列表
2. 读取多个文档中的yaml,yaml.load_all
>>> documents = """
... ---
... name: The Set of Gauntlets 'Pauraegen'
... description: >
... A set of handgear with sparks that crackle
... across its knuckleguards.
... ---
... name: The Set of Gauntlets 'Paurnen'
... description: >
... A set of gauntlets that gives off a foul,
... acrid odour yet remains untarnished.
... ---
... name: The Set of Gauntlets 'Paurnimmen'
... description: >
... A set of handgear, freezing with unnatural cold.
... """
>>> for data in yaml.load_all(documents):
... print data
{'description': 'A set of handgear with sparks that crackle across its knuckleguards.\n',
'name': "The Set of Gauntlets 'Pauraegen'"}
{'description': 'A set of gauntlets that gives off a foul, acrid odour yet remains untarnished.\n',
'name': "The Set of Gauntlets 'Paurnen'"}
{'description': 'A set of handgear, freezing with unnatural cold.\n',
'name': "The Set of Gauntlets 'Paurnimmen'"}
符号 — 用来定义同一个yaml流中的不同的文件档,用yaml.load_all可以分别读取yaml流中不同的文档,同理可以使用yaml.dump_all
>>> print yaml.dump_all([1,2,3], explicit_start=True)
--- 1
--- 2
--- 3
>>> print yaml.dump({'name': 'Silenthand Olleander', 'race': 'Human',
... 'traits': ['ONE_HAND', 'ONE_EYE']})
name: Silenthand Olleander
race: Human
traits: [ONE_HAND, ONE_EYE]
desired_caps = {'name': 'Silenthand Olleander', 'race': 'Human','traits': ['ONE_HAND', 'ONE_EYE']}
with open(yamlpath, "w", encoding="utf-8") as f:
yaml.dump(desired_caps, f)
yaml.dump接受一个python对象,并解析成一个yaml格式的字符串,并且可以由第二个参数指定要输出的文件。但是yaml.dump不能很好的处理嵌套的字典,下面的例子中嵌套的字典被解析为{}
print(yaml.dump({ 'chromeOptions': {'androidProcess': 'com.tencent.mm:tools'}}))
chromeOptions: {androidProcess: 'com.tencent.mm:tools'}
ruamel.yaml的API文档[https://yaml.readthedocs.io/en/latest/overview.html]
ruamel.yaml的用法和PyYAML基本一样,并且默认支持更新的YAML1.2版本
from ruamel.yaml import YAML
yaml=YAML(typ='safe') # default, if not specfied, is 'rt' (round-trip)
yaml.load(doc)
在这doc可以是一个文件指针(即具有 .read()方法,字符串或一个 pathlib.Path())。typ='safe’的作用是:加载文档而不解析未知标记
2. python对象转换成yaml流
from ruamel.yaml import YAML
yaml=YAML()
yaml.default_flow_style = False
yaml.dump({'a': [1, 2]}, s)
在这s可以是文件指针(即具有.write()方法的对象 ,或者pathlib.Path())
3. 旧的ruamel.yaml API
import ruamel.yaml
ruamel.yaml.load(doc, ruamel.yaml.RoundTripLoader)
ruamel.yaml.dump(code, s, Dumper=ruamel.yaml.RoundTripDumper)
import sys
from ruamel.yaml import YAML
inp = """\
# example
name:
# details
family: Smith # very common
given: Alice # one of the siblings
"""
yaml = YAML()
code = yaml.load(inp)
code['name']['given'] = 'Bob'
yaml.dump(code, sys.stdout)
输出
# example
name:
# details
family: Smith # very common
given: Bob # one of the siblings