【python】+配置文件+操作yaml文件

一、YAML配置文件

修改前

chrome_path: chromedriver.exe
jobs:
- A1
uestcedu_url: https://www.baidu.com

修改后

chrome_path: chromedriver.exe
jobs:
- A1
- A2(New)
uestcedu_url: https://www.baidu.com

 

 

二、读取YAML配置文件

#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@Time    :2022/1/10 19:39
@Author  :
@File    :JarYamlUtil.py
@Version :1.0
@Function:
"""
import yaml


class JarYamlUtil:
    def __init__(self, yaml_path=None):
        if yaml_path:
            self.yaml_file_path = yaml_path
        else:
            self.yaml_file_path = r"E:\Code\PythonCode\AnalysisReport\AnalysisReport\src\config.yaml"

    def get(self):
        """
        获取所有的数据
        @return:
        """
        return yaml.safe_load(open(self.yaml_file_path, 'r', encoding='utf-8').read())

    def update(self, yaml_value):
        """
        修改YAML数据(实质为覆盖)
        @param yaml_value: 新数据(所有的)
        """
        with open(self.yaml_file_path, 'w', encoding='utf-8') as w_f:
            # 覆盖原先的配置文件
            yaml.dump(yaml_value, w_f)


if __name__ == '__main__':
    # 获取YAML数据
    print("获取到的数据:", JarYamlUtil().get())
    # 修改YAML数据
    yaml_data = JarYamlUtil().get()
    yaml_data['jobs'].append('A2(New)')
    JarYamlUtil().update(yaml_data)
    print("修改后获取到的数据:", JarYamlUtil().get())

 

 

执行结果

 

posted @ 2020-07-28 18:10  淡怀  阅读(645)  评论(0编辑  收藏  举报