代码何在?

Python recipe(11):读取ini配置文件 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

相关文章:

  • 2021-12-20
  • 2021-11-26
  • 2019-01-15
  • 2021-10-12
  • 2021-10-14
  • 2021-09-05
  • 2022-12-23
  • 2021-10-21
猜你喜欢
  • 2021-12-26
  • 2019-11-26
  • 2022-01-20
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-16
相关资源
相似解决方案