Python读取配置文件的方法

from configparser  import ConfigParser

class GetCfg:
    """
    读取配置文件方法
    """

    def __init__(self, config_file: str, section: [str, None] = None, key: [str, None] = None):
        self.config_file = config_file
        self.conf = ConfigParser()
        self.section = section
        self.key = key
        self.conf.read(self.config_file, encoding="utf-8")

    def get(self) -> str:
        value = self.conf.get(self.section, self.key)
        return value

 

class config:
    def __init__(self):
        config = configparser.ConfigParser()
        # 工程目录
        self.project_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
        # 配置文件目录
        self.file_path = os.path.abspath(os.path.join(self.project_path, 'file.ini'))
        config.read(self.file_path)
        self.base_url = config.get("server", "base_url")

 

posted @ 2023-07-11 14:17  sunshine阿星  阅读(111)  评论(0)    收藏  举报