1.下载安装:
pip install configparser
2.说明:
configparser模块是python内置的读取写入配置的模块,该模块支持读取.conf或者.ini类文件
配置文件说明:
a)配置文件中包含一个或多个section,每个section都有自己的option
b)section用[sect_name]表示,每个option是一个健值对,使用分隔符=或:隔开
c)在option分隔符两端的空格会被忽略掉
d)配置文件使用#和;注释
一个简单的配置文件示列:
configparser 的基本属性操作:
1.实例化configparser 并加载配置文件
cp=configparser.ConfigParser()
cp.read('myapp.conf')
2.获取section列表、option健列表和option健元组列表
cp.sections() #获取配置文件的section列表
cp.options('tyzf')#获取配置文件的option健列表
cp.items('url')#获取配置文件的option健对应的值
3读取指定的配置信息
cp.get(section,option)#指定对应的section、option的值信息
4.按照类型读取配置信息
cp.getint(section,option)#按照整型读取数据
cp.getfloat(section,option#按照浮点型读取数据
cp.getboolean(section,option)#获取bool型数据
5.判断是否存在section、option
cp.has_section(section)#返回True
cp.has_option(section,option)
6.添加删除section
cp.add_section(section)#添加
cp.remove_section(section)#删除
7.设置option
cp.set('tyzf','url','https://****')
8.保存配置
cp.write(open(file),'w')
参考代码:
class ConfigIni():
def __init__(self,sFile):
self.sFile=sFile
try:
self.conf=configparser.ConfigParser()
self.conf.read(self.sFile)
except Exception as err:
raise
'''
判断sections是否存在
'''
def isExistsSection(self,sections):
if self.conf.has_section(section=sections):
return True
else:
return False
'''
判断option是否存在
'''
def isExistsOption(self,section,option):
if self.conf.has_option(section=section,option=option):
return True
else:
return False
'''
获取配置信息的数据,返回string类型
'''
def GetStrValue(self,section,option):
try:
value=self.conf.get(section,option)
return value
except Exception:
return 0
'''
获取配置信息的数据,返回int类型
'''
def GetIntValue(self,section,option):
try:
value = self.conf.getint(section,option)
return value
except Exception:
return 0
'''
获取配置信息的数据,返回float类型
'''
def GetFloatValue(self,section,option):
try:
value=self.conf.getfloat(section,option)
return value
except Exception:
return 0
'''
获取配置信息的数据,返回bool类型
'''
def GetBoolValue(self,section,option):
try:
value=self.conf.getboolean(section,option)
return value
except Exception:
return 0
'''
修改更新数据
'''
def UpdateValue(self,section,option,value):
try:
self.conf.set(section,option,value)
with open(self.sFile,'r+') as f:
self.conf.write(f)
except Exception:
return False
'''
添加数据
'''
def AddValue(self,section,option,value):
try:
self.conf.add_section(section)
self.conf.set(section,option,value)
with open(self.sFile,'r+') as f:
self.conf.write(f)
except Exception:
return False