7 | PyYAML源码之yaml.compose_all,yaml.load,yaml.load_all
- 1 yaml.compose_all()
- 2 yaml.load()
- 3 yaml.load_all()
1 yaml.compose_all()
- 源码:
- 作用:分析流中的所有
YAML
文档,并产生相应的表示树。
- 解析:
import yaml
doc = """
---
user1:
name: xiaoming
age: 23
password: 123456
---
user2:
name: xiaozhang
age: 24
password: 123456
---
user3:
name: xiaoli
age: 25
password: 123456
"""
trees = yaml.compose_all(doc)
for tree in trees:
print(tree)
MappingNode(tag='tag:yaml.org,2002:map', value=[(ScalarNode(tag='tag:yaml.org,2002:str', value='user1'), MappingNode(tag='tag:yaml.org,2002:map', value=[(ScalarNode(tag='tag:yaml.org,2002:str', value='name'), ScalarNode(tag='tag:yaml.org,2002:str', value='xiaoming')), (ScalarNode(tag='tag:yaml.org,2002:str', value='age'), ScalarNode(tag='tag:yaml.org,2002:int', value='23')), (ScalarNode(tag='tag:yaml.org,2002:str', value='password'), ScalarNode(tag='tag:yaml.org,2002:int', value='123456'))]))])
MappingNode(tag='tag:yaml.org,2002:map', value=[(ScalarNode(tag='tag:yaml.org,2002:str', value='user2'), MappingNode(tag='tag:yaml.org,2002:map', value=[(ScalarNode(tag='tag:yaml.org,2002:str', value='name'), ScalarNode(tag='tag:yaml.org,2002:str', value='xiaozhang')), (ScalarNode(tag='tag:yaml.org,2002:str', value='age'), ScalarNode(tag='tag:yaml.org,2002:int', value='24')), (ScalarNode(tag='tag:yaml.org,2002:str', value='password'), ScalarNode(tag='tag:yaml.org,2002:int', value='123456'))]))])
MappingNode(tag='tag:yaml.org,2002:map', value=[(ScalarNode(tag='tag:yaml.org,2002:str', value='user3'), MappingNode(tag='tag:yaml.org,2002:map', value=[(ScalarNode(tag='tag:yaml.org,2002:str', value='name'), ScalarNode(tag='tag:yaml.org,2002:str', value='xiaoli')), (ScalarNode(tag='tag:yaml.org,2002:str', value='age'), ScalarNode(tag='tag:yaml.org,2002:int', value='25')), (ScalarNode(tag='tag:yaml.org,2002:str', value='password'), ScalarNode(tag='tag:yaml.org,2002:int', value='123456'))]))])
2 yaml.load()
user1:
name: xiaoming
age: 23
password: 123456
user2:
name: xiaozhang
age: 24
password: 123456
user3:
name: xiaoli
age: 25
password: 123456
import yaml
with open('config_pyyaml.yaml', 'r') as f:
data = yaml.load(f, Loader=yaml.FullLoader)
print(data)
{'user1': {'name': 'xiaoming', 'age': 23, 'password': 123456}, 'user2': {'name': 'xiaozhang', 'age': 24, 'password': 123456}, 'user3': {'name': 'xiaoli', 'age': 25, 'password': 123456}}
3 yaml.load_all()
- 源码:
- 作用:解析流中的所有
YAML
文档并生成相应的Python
对象;
- 解析:
---
user1:
name: xiaoming
age: 23
password: 123456
---
user2:
name: xiaozhang
age: 24
password: 123456
---
user3:
name: xiaoli
age: 25
password: 123456
import yaml
f = open('config_pyyaml01.yaml', 'r')
docs = yaml.load_all(f, Loader=yaml.FullLoader)
for doc in docs:
print(doc)
f.close()
{'user1': {'name': 'xiaoming', 'age': 23, 'password': 123456}}
{'user2': {'name': 'xiaozhang', 'age': 24, 'password': 123456}}
{'user3': {'name': 'xiaoli', 'age': 25, 'password': 123456}}