Python yaml 详解
文章目录
- 1 概述
- 1.1 特点
- 1.2 导入
- 2 对象
- 2.1 字典
- 2.2 数组
- 2.3 复合结构
- 3 操作
- 3.1 读取
- 3.2 写入
1 概述
1.1 特点
- yaml 文件是一种数据序列化语言,广泛用于配置文件、日志文件等
- 特点:
- ① 大小写敏感。
- ② 使用缩进表示层级关系。缩进时不允许使用 Tab 键,只允许使用空格。缩进的空格数目不重要,只要相同层级的元素左侧对其即可。
1.2 导入
> pip install pyyaml
pyyaml 是第三方库,需要导入
扩展:Python 安装第三方库详解:https://blog.csdn.net/qq_34745941/article/details/106341898
2 对象
2.1 字典
# 格式1: 单个字典
key: value# 格式2:多维字典
key:child-key: valuechild-key2: value2
- 如:新建 “Demo.yaml” 文件,并输入下列配置
database:host: localhostport: 1521username: userpasswoed: 123
输出测试:(以多维字典为例)
import yamlfileName = 'Demo.yaml'# Loader 制定使用 yaml.FullLoader 解析器,更加安全
with open(fileName, mode='r', encoding='utf-8') as file:config = yaml.load(file, Loader=yaml.FullLoader)print(config)print(config['database']['username'])
输出结果:
{'database': {'host': 'localhost', 'port': 1521, 'username': 'user', 'passwoed': 123}}
user
2.2 数组
# 格式1:单个数组
- A
- B
- C# 格式2: 多维数组
-- key1- key2
-- value1- value2
输出测试:(以多维数组为例)
import yamlfileName = 'Demo.yaml'# Loader 制定使用 yaml.FullLoader 解析器,更加安全
with open(fileName, mode='r', encoding='utf-8') as file:config = yaml.load(file, Loader=yaml.FullLoader)print(config)print(config[0])
输出结果:
[['key1', 'key2'], ['value1', 'value2']]
['key1', 'key2']
2.3 复合结构
langusges:- Java- Python- Sqlperson:name: 张三age: 18
输出测试:
import yamlfileName = 'Demo.yaml'# Loader 制定使用 yaml.FullLoader 解析器,更加安全
with open(fileName, mode='r', encoding='utf-8') as file:config = yaml.load(file, Loader=yaml.FullLoader)print(config)
输出结果:
{'langusges': ['Java', 'Python', 'Sql'], 'person': {'name': '张三', 'age': 18}}
3 操作
3.1 读取
import yamlfileName = 'Demo.yaml'# Loader 制定使用 yaml.FullLoader 解析器,更加安全
with open(fileName, mode='r', encoding='utf-8') as file:config = yaml.load(file, Loader=yaml.FullLoader)print(config)
3.2 写入
import yamlfileName = 'Demo.yaml'users = [{'name': '张三', 'age': 18},{'name': '李四', 'age': 19}]with open(fileName, mode='w', encoding='UTF-8') as file:yaml.dump(users, file, sort_keys=False, allow_unicode=True)
输出结果:
- name: 张三age: 18
- name: 李四age: 19