import ConfigParser
def main():
"""
基本的读取配置文件
-read(filename) 直接读取ini文件内容
-sections() 得到所有的section,并以列表的形式返回
-options(section) 得到该section的所有option
-items(section) 得到该section的所有键值对
-get(section,option) 得到section中option的值,返回为string类型
-getint(section,option) 得到section中option的值,返回为int类型,还有相应的getboolean()和getfloat() 函数
基本的写入配置文件
-add_section(section) 添加一个新的section
-set( section, option, value) 对section中的option进行设置,需要调用write将内容写入配置文件
"""
cf = ConfigParser.ConfigParser()
cf.read('db.txt')
sec = cf.sections()
print sec
opt = cf.options('db1')
print opt
val = cf.items('db1')
print val,type(val)
val_str = cf.get('db1', 'db_host')
print val_str
cf.set('db1','db_host','192.168.1.55')
cf.write(open('db.txt','w'))
try:
cf.add_section('ttxsgoto')
cf.set('ttxsgoto', 'hostname', 'ttxsgoto')
cf.write(open('db.txt','w'))
except Exception:
pass
cf.remove_option('ttxsgoto', 'hostname')
cf.remove_section('ttxsgoto')
cf.write(open('db.txt','w'))
def write():
config = ConfigParser.RawConfigParser()
config.add_section('Section1')
config.set('Section1','an_int','15')
config.set('Section1','a_bool','true')
config.set('Section1','a_float','3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1','foo','%(bar)s is %(baz)s !')
with open('example.cfg','wb') as configfile:
config.write(configfile)
def read():
config = ConfigParser.RawConfigParser()
config.read('example.cfg')
a_float = config.getfloat('Section1', 'a_float')
an_int = config.getint('Section1', 'an_int')
print a_float + an_int
if config.getboolean('Section1', 'a_bool'):
print config.get('Section1','foo')
def read1():
config = ConfigParser.ConfigParser()
config.read('example.cfg')
print config.get('Section1', 'foo', 0)
print config.get('Section1','foo',1)
print config.get('Section1','foo',0,{'bar':'Document','baz':'evil'})
def read2():
config = ConfigParser.SafeConfigParser({'bar':'Life','baz':'hard'})
config.read('example.cfg')
print config.get('Section1','foo')
config.remove_option('Section1', 'bar')
config.remove_option('Section1','baz')
print config.get('Section1','foo')
if __name__ == '__main__':
main()