Python读取ini配置文件

配置文件ini的格式

[mysql_conf]        ; 1、在ini配置文件中,[]中的值被称为section
host = 127.0.0.1    ; 3、一个section下的键值对被称为option
port = 3306         ; 4、同一个section下也可以存在多个option,也就是多个键值对的配置项
username = root
password = 123456
[python]            ; 2、同一个ini文件中可以存在多个section
version = 3.7.8
system_env = windows

读取ini文件

from configparser import ConfigParser

# 实例化ConfigParser对象,来处理ini文件
conf = ConfigParser()
# read方法接受ini文件路径,也可以指定编码格式
print(conf.read("./data/db_conf.ini", encoding="utf-8"))

获取配置文件中对应值的基础方法

# 根据section名和option的key名来获取value
print(conf.get("mysql_conf", "host"))
# 打印所有的section名
print(conf.sections())
# 根据section名获取所有option名,也就是键值对的所有key
print(conf.options("mysql_conf"))
# 判断某个section是否存在
print(conf.has_section("name"))
# 判断某个section下的某个option是否存在
print(conf.has_option("mysql_conf", "host"))

实现一个ini配置文件读取工具类

# _*_coding:utf-8_*_

from box import Box
from configparser import ConfigParser

"""
@Time   : 2020/11/19 20:03
@Author : CarpLi
@File   : conf_tool.py
@Desc   : 读取ini配置文件
"""


class ConfTool(ConfigParser):

    def __init__(self, file, encoding="utf-8"):
        # 执行父类的构造函数
        super().__init__()
        self.read(filenames=file, encoding=encoding)

    # 获取不到section或者option,直接返回给定的默认值
    def get_or_default(self, section, option, default=None):
        if not self.has_section(section):
            return default
        elif not self.has_option(section, option):
            return default
        return self.get(section=section, option=option)

    # ini文件内容转换成dict输出
    def to_dict(self):
        _dict = {}
        for section in self.sections():
            # print(dict(conf.items("mysql_conf")))
            _option_dict = dict(conf.items(section=section))
            _dict.update({section: _option_dict})
        return _dict

    # 使用python-box模块,方便链式调用
    def __getattr__(self, item):
        _box = Box(self.to_dict())
        return getattr(_box, item)


if __name__ == '__main__':
    conf = ConfTool(file="./data/db_conf.ini")
    # 配置文件中如没有配置mysql登录名user字段,则默认取root
    print(conf.get_or_default("mysql_conf", "user", "root"))
    print(conf.to_dict())
    # 可以通过属性调用的形式,获取配置
    print(conf.mysql_conf.host)
posted @ 2020-11-26 22:35  拖延症的理想主义者  阅读(342)  评论(0编辑  收藏  举报