通过python的ConfigParse模块读写ini配置文件

python读写配置文件 ConfigParser模块是python标准库自带的读取配置文件的模块.通过他可以方便的读取配置文件.目前示例代码中的Python版本都是基于2.7版本
官网地址是,异常处理该官网页面也有介绍

配置配置格式
配置文件由section组成,然后其下是name:value或者name=value,注释项可以使用#或是;

常用选项:
config = ConfigParser.ConfigParser() //直接读取ini文件内容,初始化config实例(建立一个空的数据集实例)
config.read(filename)  //通过load文件filename来初始化config实例
config.write(open(filename,'w'))   //保存配置
config.get(section, key) //获得指定section中的key的value
config.getint(section, key)
config.getfloat(section, key)
config.getboolean(section, key)
config.set(section, key, value)  //在指定section中,添加一对key-value键值对,没有section时返回  
NoSectionError 异常
config.add_section(section) //添加sectio,若已经存在,返回 DuplicateSectionError 异常
config.remove_section(section)     //删除指定section,只有存放并移除时才会返回True,其他返回False
config.remove_option(section, key) //删除指定section的key,成功返回True, 失败返回False,不存在section时抛出NoSectionError异常
config.items(section) //返回指定section内的键值对列表(name, value) pairs
config.sections() //得到所有的section,并以列表的形式返回
config.options(section) //得到该section的所有option,也就是key=value中的key部分
config.has_section(section) //判断指定的节是否已经存在
config.has_option(section, option) //判断指定的节是否存在option,存在就返回True,否则返回False

下面是我的一个包装类代码示例:
配置文件config_demo2.conf, 内容如下:
[main]
optdata = eJwzMTAxMODlMgFSpmDKCEqZQSgLMGViyMsFAI+xBn4=
build = 1240
setup = 40400
fileexists = 000000000
qhistorymax = 50
options = 1001000010000010011010011111111000000101111101110000000010000000000100110010011041100000000210010111111113001111010100

[LiveUpdate]
interval = 15

[QuickConnect]
left = 0
top = 0
width = 424
height = 260
state = 0

[Graph]
v = 0
h = 65

[window]
left = 124
top = 69
width = 1093
height = 614
state = 0
ts = 0.5
bs = 0.5
cs = 0.75
lts = 0
rts = 0
thp = 546

[CmdWindow]
y = 0.629999995231628
w = 454
h = 377

[statuswin]
left = 383
top = 154
width = 592
height = 411
state = 0
font = "宋体", 8, [], [clWindowText], 134
color = -2147483643
ontop = 0
wrap = 0
包装类文件是config_parser.py
#!/usr/bin/env python
#encoding: utf-8
#description: a wrapper class for ConfigParser module
#date: 2015-10-29

import ConfigParser

class cConfParser:
    def __init__(self, conf_path):
        self.fpath = conf_path #配置文件路径,要求是绝对路径
        self.cf = ConfigParser.ConfigParser() #ConfigParser对象实例
        self.cf.read(self.fpath) #一启动就读取配置文件

    def __del__(self):
        #一关闭就将ConfigParser对象的内容序列化到本地配置文件中
        with open(self.fpath, 'w') as fh:
            self.cf.write(fh)
        fh.close()

    #添加指定的节
    def add_section(self, s):
        sections = self.cf.sections()
        if s in sections:
            return
        else:
            self.cf.add_section(s)

    #移除指定的节
    def remove_section(self, s):
        return self.cf.remove_section(s)

    def get(self, s, o):
        return self.cf.get(s, o)

    def set(self, s, o, v):
        if self.cf.has_section(s):
           self.cf.set(s, o, v)

    #移除指定节内的指定选项
    def remove_option(self, s, o):
        if self.cf.has_section(s):
            return self.cf.remove_option(s, o)
        return False

    #返回节内的(key, val)列表
    def items(self, s):
        return self.cf.items(s)

    #返回所有节的列表
    def sections(self):
        return self.cf.sections()

    #返回节内的key列表
    def options(self, s):
        return self.cf.options(s)

if __name__ == '__main__':
    config_file = './config_demo2.conf'
    cp = cConfParser(config_file)
    print cp.sections()
    print cp.items('CmdWindow')
    print cp.options('CmdWindow')
    print cp.get('main', 'optdata')
    print cp.get('LiveUpdate', 'Interval')
    cp.set('LiveUpdate', 'Retry', '3')
    print cp.remove_option('LiveUpdate', 'Retry')
    cp.set('LiveUpdate', 'Confirm', 'yes')
    cp.add_section('Copyright')
    print cp.remove_section('Copyright')
    cp.add_section('Copyright2')
下面是运行截图

打开配置文件config_demo2.conf, 你会发现其内容已经被更新了.

参考文献
http://my.oschina.net/flymaxty/blog/222748  不过是python 3写的
http://blog.sina.com.cn/s/blog_3fe961ae0102uwj9.html  有 RawConfigParser类的使用示例
http://www.jb51.net/article/68680.htm  包装了一个configurationparser类,有参考价值,但是需要修改,发现写得很不规范。
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值