读取
读取ini配置文件需要使用Python3自带的configparser库,使用示例如下
from configparser import ConfigParser # Python2中是from ConfigParser import ConfigParser
conf = ConfigParser() # 需要实例化一个ConfigParser对象
conf.read('config.ini') # 需要添加上config.ini的路径,不需要open打开,直接给文件路径就读取,也可以指定encoding='utf-8'
print(conf['user']['name']) # 读取user段的name变量的值,字符串格式
conf对象每个section段的数据类似于一个字典,可以使用[‘变量名’]或者.get(‘变量名’)获取对应的值,获取到的是字符串格式。
其他常用的读取方法如下:
conf.sections(): 获取所有的section名,结果[‘user’, ‘mysql’, ‘log’]
conf['mysql']['port']: 获取section端port变量的值,字符串格式
conf['mysql'].get('port'): 同上,字符串格式
conf.get('mysql', 'port'): 同上,字符串格式
conf['mysql'].getint('port'): 获取对应变量的整型值
conf['mysql'].getfloat('port'): 获取对应变量的浮点型值
conf['user'].getboolean('is_admin'): 获取对应变量的布尔值,支持配置为yes/no, on/‘off, true/false 和 1/0,都可以转化为Python中的True/False
conf.has_section(section):检查是否有该section
conf.options(section):输出section中所有的变量名
conf.has_option(section, option):检查指定section下是否有该变量值
如果想遍历一个section所有的变量和值,可以像遍历字典意义操作,示例如下。
for key, value in conf['mysql'].items():
print(key, value)
注意:ini文件中的变量名是大小写不敏感的,而Section名是大小写敏感的。