前言
使用配置文件可以在不修改程序的情况下,做到对程序功能的定制。Python 使用自带的configParser模块可以很方便的读写配置文件的信息。
configParser
支持的方法
ConfigParser模块支持很多种读取数据的方法,最常用的是get方法,通过section 及 option的值获取对应的数据
- read(filename) - - 直接读取文件内容
- sections() - - 得到所有的section,并以列表的形式返回
- options(section) - - 得到该section的所有option
- items(section) - - 得到该section的所有键值对
- get(section,option) - - 得到section中option的值,返回为string类型
- getint(section,option) - - 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数。
因为是内置模块,所以可以很方便的查看源码,如博主电脑中该模块在D:\Python3\Lib\configparser.py,有兴趣的可以看看源码的实现方式。
下面介绍一些实际使用。
配置文件内容
首先我们新建一个文件,如config.ini,或者config.conf,内容如下
[broswer_name] broswer = 'firefox'[server] server = 'http://www.baidu.com/'
封装
import configparser
import osclass ConfigRead(object):@staticmethoddef get_value():# file_path = os.path.dirname(os.path.realpath(__file__)) + os.path.join(r'\config','config.ini')file_path = os.path.abspath(os.path.join('config', 'config.ini'))config = configparser.ConfigParser()config.read(file_path)# print file_pathbrowser = config.get("broswer_name", "broswer") # 分别代表所在区域名 和变量名url = config.get("server", "server")return browser, urlif __name__ == '__main__':trcf = ConfigRead()print(trcf.get_value())
获取文件路径
博主的config文件放在config文件夹中,试过很多方式来获取文件绝对路径,如下方式最佳
- os.path.abspath(os.path.join('config','config.ini'))