Python配置处理ini文件-configparser

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

转载于:https://www.cnblogs.com/qixc/p/9848463.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值