0
点赞
收藏
分享

微信扫一扫

python解析yaml文件

1、初始化yaml文件的目录

  def __init__(self):
self.yaml_root_path = 'D:\\Code\\PythonProject\\UIAutoProject\\config\\yaml\\'

2、读取yaml文件的方法

    def read_yaml(self, file_path):
"""
读取yaml文件内容
:param file_path: 文件路径
:return: 解析后的yaml文件数据
"""
with open(self.yaml_root_path + file_path, mode='r', encoding='utf-8') as f:
return yaml.load(stream=f, Loader=yaml.FullLoader)

运行结果

python解析yaml文件_数据

3、写入输入到yaml文件中

    def write_yaml(self, data, file_path, is_append):
"""
向yaml文件中写入数据
:param data: 需要写入的数据
:param file_path: 写入的文件路径
:param is_append: 数据是否追加到yaml文件
:return: 无
"""
# 数据样例 test_data = [dict(test=dict(username='王', password='654')), dict(test=dict(username='柯', password='321'))]
if is_append:
mode = 'a'
else:
mode = 'w'
with open(file=self.yaml_root_path + file_path, mode=mode) as f:
yaml.dump(data=data, stream=f, allow_unicode=True, sort_keys=False, default_flow_style=False)

4、清空yaml文件的内容

    def truncate_yaml(self, file_path):
"""
清空yaml文件内容
:param file_path:
:return: 无
"""
with open(file=self.yaml_root_path + file_path, mode='w') as f:
f.truncate()

举报

相关推荐

0 条评论