Python recipe(11):读取ini配置文件

代码何在?

div css xhtml xml Example Source Code Example Source Code [http://www.cnblogs.com/tomsheep/]
'''
Created on 2010-5-22

@author: lk
'''
import ConfigParser

_defalt_config = {
    'info.name':'Kang Liu',
    'info.nick':'tomsheep',
    'favor.book':'StoneStory',
    'favor.language':'Python'}

def LoadConfig(filename, config={}):
    config = config.copy()
    cp = ConfigParser.ConfigParser()
    cp.read(filename)
    for sec in cp.sections():
        sec_name = sec.lower()
        for opt in cp.options(sec):
            config[sec_name + '.' + opt.lower()] = cp.get(sec, opt).strip()

    return config
if __name__ == '__main__':
    config = LoadConfig("config.ini", _defalt_config)
    print config

以上代码改写自Python Cookbook 4-12

概述:

    利用ConfigParser模块读取ini文件,返回一个字典。ini文件的格式为

[section1]

option1 = value1

option2 = value2

[section2]

option1 = value1

option2 = value2

代码说明:

1.ConfigParser对象的sections函数返回所有section的列表,options(sec)函数返回该sec下所有option的列表,get(sec,opt)函数返回sec区块下opt选项的值。

更多ConfigParser请见:ConfigParser in Python

posted on 2010-05-22 23:50  tomsheep  阅读(557)  评论(0编辑  收藏  举报

导航