ConfigParser模块的常用方法
read(filename) 直接读取ini文件内容
sections() 得到所有的section,并以列表的形式返回
options(section) 得到该section的所有option
items(section) 得到该section的所有键值对
get(section,option) 得到section中option的值,返回为string类型
getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数
使用方法举例,以上述方法中的两个举例:
import os
import configparser
def get_config_section_list():
config = configparser.ConfigParser()
config.read(configFilePath)
return config.sections()
def get_config_values(section, option):
config = configparser.ConfigParser()
config.read(configFilePath)
return config.get(section=section, option=option)
rootDir = os.path.split(os.path.realpath(__file__))[0]
# config.ini文件路径
configFilePath = os.path.join(rootDir, './config.txt')
section_lst = get_config_section_list()
log_path_list = []
for i in section_lst:
log_path = get_config_values(i, 'log_path')
log_path_list.append([i,log_path])
print log_path_list
运行结果:
[[u’test’, u’./input’], [u’test2’, u’./input’]]
config.txt:
[test]
log_path = ./input
[test2]
log_path = ./input