python读取ini的配置文件

configparser模块简介:

configparser模块是用来解析ini配置文件的解析器。

ini配置文件的结构如x下图

ini文件结构需要注意以下几点:

键值对可用=或者:进行分隔

section的名字是区分大小写的,而key的名字是不区分大小写的

键值对中头部和尾部的空白符会被去掉

值可以为多行

配置文件可以包含注释,注释以#或者;为前缀

 

操作步骤:

1、导入python的内置 configparser 库

import configparser

2、在项目名下新建一个config文件夹,然后再新建一个config.ini文件,然后放入配置的数据;如下图:

python 引入配置文件 python导入配置文件_配置文件

 

 

3、在新建一个config_utils.py文件;编写python代码读取ini的配置文件;

@property装饰器负责把类中的方法转换成属性来调用

代码示例:

# 读取配置文件
import  os
import  configparser

current_path=os.path.dirname(__file__)
config_path=os.path.join(current_path,'../config/config.ini')

class ConfigUtils():
    def __init__(self,path=config_path):
        self.cfg=configparser.ConfigParser()
        self.cfg.read(path,encoding='utf-8')

    #@property装饰器负责把类中的方法转换成属性来调用
    @property
    def get_url(self):
        value=self.cfg.get('default','url')
        return value

    @property
    def get_driver_path(self):
        value=self.cfg.get('default','driver_path')
        return value

#封装一个读取配置文件的对象
local_config=ConfigUtils()

if __name__=='__main__':
    print(local_config.get_url)
    print(local_config.get_driver_path)

查看执行结果:

python 引入配置文件 python导入配置文件_配置文件_02