# yaml文件读取
# 创建yaml文件
# 语法规则:字典类型的数据 键: 值 冒号后要空格
文件名:test.yaml
文件内容:
id: 1
name: '张三'
age: 18
sex: '女'
import yaml # 打开文件 f = open('./data/test.yaml','r',encoding='utf-8') # 读取yaml数据 data = yaml.load(f,yaml.FullLoader) print(data) name = data.get('name') name = data['name'] print(name) f.close()
# 打开文件
文件名:test1.yaml
文件内容:
- 1
- '秋水'
- 18
- 女
with open('./data/test1.yaml','r',encoding='utf-8') as f: data = yaml.load(f,yaml.FullLoader) name = data[1] print(name)
# 做项目的时候,交互[{}]
文件名:test2.yaml
文件内容:
-
id: 1
name: '虚竹'
age: 33
sex: '男'
-
id: 2
name: '小龙女'
age: 33
sex: '男'
with open('./data/test2.yaml','r',encoding='utf-8') as f: data = yaml.load(f,yaml.FullLoader) name = data[1].get('name') name1 = data[0]['name'] print(name,name1)
# 做项目的时候,交互[{}]
文件名:test3.yaml
文件内容:
-
id: 1
name: '球会'
age: 18
sex: '女'
data:
address: '长沙'
status: 'success'
-
id: 1
name: 'hui会'
age: 18
sex: '女'
data:
address: '长沙1'
status: 'success'
with open('./data/test3.yaml', 'r', encoding='utf-8') as f: data = yaml.load(f, yaml.FullLoader) name = data[1]['data']['address'] print(name)