今天迎来了2013的第一场大雪,离2002年的第一场雪已经过去11年了,真真切切的感受到什么是弹指一挥间。最近工作中用到了CP模块,顺便就总结一下。
#!/usr/bin/env python
import ConfigParser as cp
def read(cf):
for section in cf.sections():
print '[' + section + ']'
for option in cf.options(section):
print option + "=" + cf.get(section,option)
if __name__== '__main__':
cf = cp.ConfigParser()
cf.read('aa.ini')
##Read
read(cf)
##Modify
cf.add_section('test')
cf.set('test', 'key1', 'value1')
cf.set('test', 'key2', 'value2')
##Read
read(cf)
##Write
cf.write(open("aa.ini", "w"))
1)常见的方法列表,如dir(ConfigParser.ConfigParser):
['OPTCRE', 'OPTCRE_NV', 'SECTCRE', '_KEYCRE', '__doc__', '__init__', '__module__', '_boolean_states'
, '_get', '_interpolate', '_interpolation_replace', '_read', 'add_section', 'defaults', 'get', 'getb
oolean', 'getfloat', 'getint', 'has_option', 'has_section', 'items', 'options', 'optionxform', 'read
', 'readfp', 'remove_option', 'remove_section', 'sections', 'set', 'write']
2)ConfigParser模块包含3个类:ConfigParser、RawConfigParser、SafeConfigParser,RawCnfigParser是最基础的INI文件读取类,ConfigParser、SafeConfigParser支持对%(value)s变量的解析。 当配置文件有些特殊字符时,需要用到RawConfigParser,这里我遇到的情况是日志的配置
##RawConfigParser
cf = cp.ConfigParser()
cf.read('bb.ini')
read(cf)
cf = cp.RawConfigParser()
cf.read('bb.ini')
read(cf)
[website]
url=http://localhost:80/
host=localhost
port=80
[website]
url=http://%(host)s:%(port)s/
host=localhost
port=80