当前位置: 首页 > 工具软件 > ini-parser > 使用案例 >

python封装configparser 读取ini配置文件

逑禄
2023-12-01

1、ini文件说明

        ini文件由节(section)、键(option)、值(value)组成,如下:

[Mysql]
host=10.11.1.1
port=3306

;我是注释,以分号开头的就是注释
;system就是节section
[System]
;host就是键option,=号后边是value值
host=10.11.1.1
port=443
user=test
passwd=test!@#
proxies=None

2、python封装

# 这个log封装的样例可以参考:这是一个我会补上的链接
# 可以先试用print
from common import log
import configparser
import os


log = log.Logs()


class IniCfg:

    def __init__(self):

        self.conf = configparser.RawConfigParser()

        # 配置文件路径
        proDir = os.path.split(os.path.realpath(__file__))[0]
        self.cfgpath = os.path.join(proDir, "config.ini")

    # 检查section是否存在
    def checkSection(self, section):
        try:
            self.conf.read(self.cfgpath)
            self.conf.items(section)
        except configparser.NoSectionError:
            log.error(">> 无此section,请核对[%s]" % section)
            return None
        return True

    # 获取option值
    def readOption(self, section, option):
        # self.checkSection(section)
        try:
            self.conf.read(self.cfgpath)
            self.checkSection(section)
            v = self.conf.get(section, option)
            return v
        except configparser.NoOptionError:
            log.error(">> 无此option,请核对[%s]" % option)
        return None

    # 获取所有的section
    def readSectionItems(self):
        self.conf.read(self.cfgpath, encoding="utf-8")
        return self.conf.sections()

    # 读取一个section,list里面对象是元祖
    def readOneSection(self, section):
        try:
            item = self.conf.items(section)
        except configparser.NoSectionError:
            print(">> 无此section,请核对[%s]" % section)
            return None
        return item

    # 读取一个section到字典中
    def prettySecToDic(self, section):
        if not self.checkSection(section):
            return None
        res = {}
        for key, val in self.conf.items(section):
            res[key] = val
        return res

    # 读取所有section到字典中
    def prettySecsToDic(self):
        res_1 = {}
        res_2 = {}
        sections = self.conf.sections()
        for sec in sections:
            for key, val in self.conf.items(sec):
                res_2[key] = val
            res_1[sec] = res_2.copy()
            res_2.clear()
        return res_1

    # 删除一个 section中的一个item(以键值KEY为标识)
    def removeItem(self, section, key):
        if not self.checkSection(section):
            return
        self.conf.remove_option(section, key)

    # 删除整个section这一项
    def removeSection(self, section):
        if not self.checkSection(section):
            return
        self.conf.remove_section(section)

    # 添加一个section
    def addSection(self, section):
        self.conf.add_section(section)

    # 往section添加key和value
    def addItem(self, section, key, value):
        if not self.checkSection(section):
            return
        self.conf.set(section, key, value)

 类似资料: