configparser模块
配置文件
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = hg
[topsecret.server.com]
Port = 50022
ForwardX11 = no
import configparser
conf =configparser.ConfigParser()
conf.read('test.ini') #读取文件
print(conf.sections()) #打印除默认部分外所有部分
print(list(conf['DEFAULT'])) #默认下所有键
print(conf['bitbucket.org']['user']) #section下所有键不区分大小写
#用字典方法查看section元素
#conf.get_section('DEFAULT')
conf.has_section('group') #判断是否存在section
conf.add_section('group') #增加section
conf.set('group','k1','11122') #增加或修改键值
conf.add_section('group1')
conf.set('group1','k1','23122')
conf.set('group','k2','a3122')
conf.options('group') #获取所有键(默认部分的键值所有部分都会有)
conf.items('group') #获取所有键值对
conf.get('group','k1') #获取指定键的值
conf.remove_section('group1') #删除指定section
conf.remove_option('group','k2') #删除指定键
print(conf.sections())
print(conf.items('group'))
conf.write(open('test.ini','w'))
['bitbucket.org', 'topsecret.server.com']
['serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
hg
['bitbucket.org', 'topsecret.server.com', 'group']
[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('k1', '11122')]
#新建一个配置文件
import configparser
conf = configparser.ConfigParser()
conf['DEFAULT'] = {'SeverPort':'8080',
'Fontsize':'15',
'Bgcolor':'red'
}
conf['thisisatest.com'] = {}
conf['thisisatest.com']['User']='bob'
conf['atestweb.server.cn'] = {}
top1 = conf['atestweb.server.cn']
top1['Host Port'] = '52051'
top1['Forward'] = 'no'
conf['DEFAULT']['Forward'] = 'yes'
with open('test1.ini','w') as conffile :
conf.write(conffile)