python菜鸟级配置文件封装

from configparser import ConfigParser


class HandleConfig:
    """
    封装配置文件类
    """
    def __init__(self, filename):
        self.filename = filename
        self.config = ConfigParser
        self.config.read(self.filename, encoding='utf-8')

    def get_config(self, section, option):
        """
        获取配置文件
        :return:
        """
        return self.config.get(section, option)

    def get_int(self, section, option):
        """
        获取int类型的数据
        :return:
        """
        return self.config.getint(section, option)

    def get_float(self, section, option):
        """
        获取float类型的数据
        :param section:
        :param option:
        :return:
        """
        return self.config.getfloat(section, option)

    def get_boolean(self, section, option):
        """
        获取bool类型的数据
        :param section:
        :param option:
        :return:
        """
        return self.config.getboolean(section, option)

    def get_eval_value(self, section, option):
        """
        获取python内置类型
        :param section:
        :param option:
        :return:
        """
        return eval(self.get_config(section, option))

    @classmethod
    def write_config(self,datas, filename):
        """
        写入配置文件
        :param datas:
        :param filename:
        :return:
        """
        # 判断是否为嵌套字典的字典
        if isinstance(datas, dict):
            for value in datas.values():
                if not isinstance(value, dict):
                    return

            config = ConfigParser
            for key in datas:
                config[key] =datas[key]
            with open(filename, 'w')as file:
                config.write(file)

猜你喜欢

转载自www.cnblogs.com/xingyunqiu/p/11242486.html
今日推荐