python学习14:如何读取yaml文件?
yaml是专门用来写配置文件的语言,类似于json格式,是python自动化中常见的一种数据驱动的方式
1)读取数据:
# 方法一(推荐)
filename = r'D:\stdutyZiLiao\pythoneProjects\webUI\逻辑流程\test006.yaml'
with open(file=filename,mode='r+',encoding='utf-8') as f :
# yaml.load()
all_info = yaml.load(f,Loader = yaml.Loader)
print(all_info) # {'key': '字典', 'msg': {'key1': 'value1', 'key2': 'value2'}, 'info': [1, 2, 3, 4, 6]}
# 方法二
f = open(file=filename,mode='r+',encoding='utf-8')
all_info = yaml.load(f,Loader = yaml.Loader)
print(all_info)
f.close()
2)写入数据:
# 写入数据
# 1.数据源
# 2.写入到什么文件
TestCase = {
'case1':{
'casename': '登陆成功用例',
'username': 'xx1',
'pwd': '12345',
'msg': '登录成功'
},
'case2':{
'casename': '登陆失败用例',
'username': 'xxxxx1',
'pwd':'12345',
'msg':'登录失败'
}
}
with open(file=filename,mode='w+',encoding='utf-8') as f:
yaml.dump(TestCase,f,allow_unicode=True) # 是否支持unicode格式:是