yaml文件的读写
读取:
import yaml
# 该方法也可以放到conftest配置文件中
def get_yaml_data(file_path, key=None):
with open(file_path, encoding='utf-8') as f:
yaml_data = yaml.safe_load(f)
if key:
level_data = yaml_data.get(key)
return level_data
else:
return yaml_data
if __name__ == '__main__':
filepath = 'D:\\python_workspace\\autotest\homework\\task_app\\test_datas\\member_names.yml'
data = get_yaml_data(filepath)
print(data)
写入:
可参考资料:https://www.cnblogs.com/jiahm/p/13811218.html
#!/usr/bin/python3.8.9
# -*- coding: utf-8 -*-
# @Author : Tina Yu
# @Time : 2022-1-9 12:56
import yaml
from utils.generate_info import GenerateInfo
def write_to_yaml(count):
member_info_list = []
for i in range(count):
name = GenerateInfo.get_user_name()
phone_num = GenerateInfo.get_phone_num()
member_info = {'name': name, 'phone_num': phone_num}
member_info_list.append(member_info)
return member_info_list
def generate_member_info(count):
"""生成成员数据,并写入成员数yaml文件中"""
test_add_member_manual_data = write_to_yaml(count)
test_add_member_manual_and_continue_data = write_to_yaml(count)
doc = [{'test_add_member_manual': test_add_member_manual_data},
{'test_add_member_manual_and_continue': test_add_member_manual_and_continue_data},
{'test_delete_member_by_search': test_add_member_manual_data}]
filename = './test_member_info.yml'
with open(filename, 'w', encoding="utf-8") as f:
# 写入非“---”分隔的文档时,使用yaml.safe_load、yaml.safe_dump即可,同时不需要转换类型default_flow_style=False
# 写入“---”分隔的文档时,使用yaml.safe_load_all、yaml.safe_dump_all即可
# allow_unicode=True可以解决中文乱码问题
yaml.safe_dump(doc, f, allow_unicode=True, default_flow_style=False)
if __name__ == '__main__':
# todo 当前手动执行,后期改为在session级别启动时初始化一次
generate_member_info(3)
本文来自博客园,作者:于慧妃,转载请注明原文链接:https://www.cnblogs.com/fengyudeleishui/p/15780730.html