pythonmokuai/ target=_blank class=infotextkey>python模块configobj读取ini配置文件
代码:
#!/usr/bin/python
#
# -*- coding:utf-8 -*-
import string
from configobj import ConfigObj
class IniFileOperator:
def __init__(self):
self.inifile = "config.ini"
#获取ini参数值
def get_ini_val(self,inifile,section,option):
config = ConfigObj(inifile)
val=config[section][option]
if val!=None and val!="":
return val
else:
return False
#获取ini键值
def get_ini_option(self,inifile,section):
config = ConfigObj(inifile)
sect = config.keys()
if sect.count(section) :
option = config[section]
return option.keys()
else :
return ""
#获取ini选项
def get_ini_section(self,inifile):
config = ConfigObj(inifile)
section = config.keys()
#print 'sections:', section
return section
#修改ini段值
def set_ini_section(self,inifile,section):
config = ConfigObj(inifile)
config[section] = {}
print "set ini_section is: ",section
config.write()
#修改ini键值
def set_ini_val(self,inifile,section,option,val):
config = ConfigObj(inifile)
sect = config.keys()
if sect.count(section) :
config[section][option] = val
print "set ini_option is: %s = %s" %(option,val)
else :
config[section] = {}
config[section][option] = val
print "set ini_option is: %s = %s" %(option,val)
config.write()
#删除ini键值
def del_ini_option(self,inifile,section,option):
config = ConfigObj(inifile)
sect = config[section]
if sect.keys().count(option) :
del config[section][option]
print "delete ini_option is: %s" %option
config.write()
configobj下载地址 :http://www.voidspace.org.uk/python/configobj.html