使用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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哈希哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值