论坛首页 编程语言技术论坛

用ConfigObj读写配置文件

浏览 4693 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2008-09-12   最后修改:2010-03-14

python优秀的库资源确实很多,最近发现了一个简单而又强大的读写配置文件的lib,地址在这里 http://www.voidspace.org.uk/python/configobj.html ,我觉得最大的亮点在于自带的格式校验功能,并且支持复杂的嵌套格式,而且使用起来也相当的简便,按教程来如下:

读文件

from configobj import ConfigObj
config = ConfigObj(filename)
#
value1 = config['keyword1']
value2 = config['keyword2']
#
section1 = config['section1']
value3 = section1['keyword3']
value4 = section1['keyword4']
#
# you could also write
value3 = config['section1']['keyword3']
value4 = config['section1']['keyword4']

 

写文件

from configobj import ConfigObj
config = ConfigObj()
config.filename = filename
#
config['keyword1'] = value1
config['keyword2'] = value2
#
config['section1'] = {}
config['section1']['keyword3'] = value3
config['section1']['keyword4'] = value4
#
section2 = {
    'keyword5': value5,
    'keyword6': value6,
    'sub-section': {
        'keyword7': value7
        }
}
config['section2'] = section2
#
config['section3'] = {}
config['section3']['keyword 8'] = [value8, value9, value10]
config['section3']['keyword 9'] = [value11, value12, value13]
#
config.write()

 
更详细的信息可以参阅下doc,蛮详尽的

 

论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics