使用python的configparser操作.ini配置文件


.ini配置文件一般如下图所示

configparser模块操作配置文件,主要实现获取配置文件所有的域,返回包含所有域名称的list(如上图mailtitle、connet、sender、receiver都是域名),获取域的所有key,获取域的所有value,获取域的key-value,获取域的指定key的value,获取域的指定value的key

具体代码如下
# -* - coding: UTF-8 -* -
import configparser,os

class configKV(object):
"""
获得path文件的所有section(域)
file:配置文件路径
"""
def getSections(self,file): #获取配置文件中所有的域
conf = configparser.ConfigParser()
conf.read(self.getAbsolute_path('config')+file,encoding="utf-8")
sections=conf.sections()
return sections

#获取配置文件的绝对路径,package:目标目录
def getAbsolute_path(self,package):
proDir = os.path.split(os.path.realpath(__file__))[0]
configPath = os.path.join(proDir)
path = os.path.abspath(configPath)
p=path.replace('tools',package)
return p+'\'
"""
获得section域的所有key
file:配置文件路径
section:域名
config:配置文件所在文件名
"""
def getKeys(self,file,section,config):
conf = configparser.ConfigParser()
conf.read(self.getAbsolute_path(config)+file,encoding="utf-8") #读取配置文件
keys=conf.options(section) #获取域下的所有key
return keys

"""
得到指定section的所有键值对
path:配置文件路径
section:域名
"""
def getKeys_values(self,file,section):
conf = configparser.ConfigParser()
filepath=self.getAbsolute_path('config') + file
conf.read(filepath,encoding="utf-8")
kvs = conf.items(section) #获取域下的所有键值对[('a',1),('b',2)]
kvdict={}
for kv in kvs:
kvdict[kv[0]]=kv[1]
return kvdict

"""
得到指定section的所有值
path:配置文件路径
section:域名
"""
def getValues(self,file,section):
conf = configparser.ConfigParser()
conf.read(self.getAbsolute_path('config')+file,encoding="utf-8")
kvs = conf.items(section) #获取键值对
value_list=[]
for kv in kvs:
value_list.append(kv[1])
return value_list

"""
获取指定key的value
"""
def getvalue(self,file,section,key):
kv=self.getKeys_values(file,section) #调用现有的获取键值对的函数
for k in kv.keys():
if(key==k): #检测传入的key是否存在
value=kv[key]
return value
return None

"""
获取指定value值的key
"""
def getkey(self,file,section,value):
conf = configparser.ConfigParser()
conf.read(self.getAbsolute_path('config')+file, encoding="utf-8")
kv = self.getKeys_values(file,section) #调用现有的获取键值对的函数
for key in kv.keys():
v=kv[key]
if(v==value): #检测传入的value是否存在
return key
return None

原文地址:https://www.cnblogs.com/shuyichao/p/10384293.html