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

本文介绍了Python中用于读写INI配置文件的ConfigObj模块,提供了详细的代码示例,包括获取、设置、删除配置项以及修改配置段的功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值