用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。在python2.x版本中为ConfigPsresr
来看一个好多软件的常见文档格式如下
[DEFAULT] serveraliveinterval = 45 compression = yes compressionlevel = 9 forwardx11 = yes [bitbucket.org] user = hg [topsecret.server.com] host port = 50022 forwardx11 = no
如果想用python生成一个这样的文档怎么做呢?
import configparser
config=configparser.ConfigParser()#生成一个处理对象
config['DEFAULT']={'ServerAliveInterval':'45',
'Compression':'yes',
'CompressionLevel':'9'}
config['bitbucket.org']={}
config['bitbucket.org']['User']='hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'
topsecret['ForwardX11'] = 'no'
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini','w') as configfile:
config.write(configfile)
写完了还可以再读出来
import configparser
config=configparser.ConfigParser()#生成一个处理对象
config.read('example.ini')
print(config.defaults())
print(config.sections())
print('bitbucket.org' in config)
print('bytebong.com' in config)
print(config['bitbucket.org'])
print(config['bitbucket.org']['user'])
topsecret=config['topsecret.server.com']
print(topsecret['ForwardX11'])
for key in config['topsecret.server.com']: print(key)
import configparser
config=configparser.ConfigParser()#生成一个处理对象
config.read('example.ini')
options = config.options('topsecret.server.com')
print(options)
item_list = config.items('DEFAULT')
print(item_list)
val=config.get('bitbucket.org','user')
print(val)
configparser增删改查语法
import configparser
config=configparser.ConfigParser()#生成一个处理对象
config.read('example.ini')
sec=config.remove_section('bitbucket.org')
config.write(open('example1.cfg', "w"))
print(config.has_section('topsecret.server.com'))
print(config.has_section('server.com'))
sec=config.add_section('wupeiqi')
config.write(open('example2.cfg', "w"))
config.remove_option('topsecret.server.com','forwardx11')
config.write(open('example3.cfg', "w"))
http://www.cnblogs.com/ming5218/p/7965973.html