YAML
字符流是将多个文档放在同一个文件中,通过“—”
分隔符进行分割;---
user1:
name: xiaoming
age: 23
password: 123456
---
user2:
name: xiaozhang
age: 24
password: 123456
---
user3:
name: xiaoli
age: 25
password: 123456
“—”
分隔符作为开始标志;YAML
对象。PyYAML
库读取YAML
字符流;load_all
函数,将字符流中的每个文档解析为YAML
对象;# -*- coding:utf-8 -*-
# 作者:虫无涯
# 日期:2023/7/28
# 文件名称:yaml_read01.py
# 作用:字符流解析
# 联系:VX(NoamaNelson)
# 博客:https://blog.csdn.net/NoamaNelson
import yaml
# 读取YAML字符流
stream = open('config_zifuliu.yaml', 'r')
docs = yaml.load_all(stream, Loader=yaml.FullLoader)
# 解析多个文档
for doc in docs:
print(doc)
# 关闭文件流
stream.close()
{'user1': {'name': 'xiaoming', 'age': 23, 'password': 123456}}
{'user2': {'name': 'xiaozhang', 'age': 24, 'password': 123456}}
{'user3': {'name': 'xiaoli', 'age': 25, 'password': 123456}}
带 ID 的节点
# 带 ID 的节点
- id: 1
name: xiaoli
age: 33
- id: 2
name: xiaowang
age: 44
对象属性的定义
# 定义一个 student 对象
- person:
id: 1
name: xiaozhagn
age: 45
列表属性的定义
# 定义一个列表
- person:
- xiaozhang
- xiaoli
- xiaowang
属性的嵌套
# 定义一个嵌套的对象
- person:
id: 123
name: xiaowang
age: 99
grades:
math: 100
science: 100
history: 100
YAML
代码的可读性和可维护性更高。# 块缩进级别为 0
name: John
age: 25
address:
street: 123 Main St
city: Anytown
state: CA
zip: 12345
# 使用 '+' 扩大缩进级别
- name: Jane
age: 30
address:
+street: 123 Main St
+city: Anytown
+state: CA
+zip: 12345
# 使用 '-' 缩小缩进级别
- name: Bob
age: 35
-address:
street: 123 Main St
city: Anytown
state: CA
zip: 12345
# 嵌套块使用不同的符号
people:
+ - name: Alice
+ age: 40
+ address:
+ city: Anytown
+ street: 123 Main St
- - name: Eve
- age: 45
- address:
- city: Anytown
- street: 123 Main St