python 读取ini配置文件模块 configobj 介绍

下面是我写的关于这个模块使用的一些代码:(仅供参考)

 

# -*- 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

你可能感兴趣的:(python,python,ini,ini,配置文件)