Python 中 Yaml 配置文件模块的使用

简介

YAML 是 “YAML Ain’t a Markup Language” 的缩写。在开发这种语言时,YAML 的意思是 “Yet Another Markup Language”,但为了强调这种语言以数据做为中心,而不是以标记语言为重点,而用反向缩略语重命名。

相较于 XML,YAML 可以基于流来处理,表达性强,扩展性好。

简要的语法规则可以概括为:

结构通过空格缩进来展示,列表里的项用”- “(dash then space) 来代表,字典中的键值对用”: “(colon then space)分隔。

更多的语法规则可以参见:

YAML 官方 Github 仓库:https://github.com/yaml/pyyaml

YAML 教程:https://pyyaml.org/wiki/PyYAMLDocumentation

文件

单个文件不需要显式分隔,直接写文件内容即可,如:

1
2
3
- Multimedia
- Internet
- Education

文件以 --- 开头,以 ... 结束,如:

1
2
3
4
5
---
- Afterstep
- CTWM
- Oroborus
...

多个文件的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
---
- Ada
- APL
- ASP

- Assembly
- Awk
---
- Basic
---
- C
- C# # Note that comments are denoted with ' #' (space then #).
- C++
- Cold Fusion

序列块

字典用 “: “ 来表示,读入 Python 中是个 dict

1
2
3
name: rosmantis
age: 2
job: tester

列表用 “- “来表示,读入 Python 中是个 list

1
2
3
- rosmantis
- 2
- tester

复合结构:

1
2
3
4
5
6
7
8
9
name: simclr
channels:
- pytorch
- anaconda
dependencies:
- cudatoolkit=10.1
- numpy=1.18.1
- opencv=3.4.2
- pillow=7.0

读写文件

读取 yml 文件:

1
2
3
4
5
6
7
import yaml
f = open(r'config.yaml')
y = yaml.load(f)

# default load 会有 userwarning, 所以可以用以下格式代替
with open('config.yaml') as f:
config = yaml.load(f, Loader=yaml.FullLoader)

写入 yml 文件:

yaml.dump 将一个 Python 对象生成为 yaml 文档

1
2
3
4
5
6
7
8
9
10
11
12
13
import yaml
file = {
'name': 'rosmantis',
'age': '2',
'hobbies': ['computer game', 'badminton']
}
yaml.dump(file, f)
# f 处需要是打开的文本文件, 如
f = open(r'config.yml', 'w')

# 另一种格式
with open('config.yml', 'w') as f:
yaml.dump(file, f)

Python 中 Yaml 配置文件模块的使用
https://pandintelli.github.io/2022/01/17/The-application-of-yaml-in-python/
作者
Pand
发布于
2022年1月17日
许可协议