1 生成配置文件
conf = configparser.ConfigParser()
conf["DEFAULT"] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9',
'ForwardX11':'yes'
}
conf['bitbucket.org'] = {'User':'hg'}
conf['topsecret.server.com'] = {
'Host Port':'50022',
'ForwardX11':'no'
}
with open('example.ini', 'w') as configfile:
conf.write(configfile)
2 读取或修改配置文件
2.1 查找
import configparser
conf = configparser.ConfigParser()
print(conf.sections())
conf.read('example.ini')
print('bytebong.com' in conf)
print('bitbucket.org' in conf)
print(conf['bitbucket.org']["user"])
print(conf['DEFAULT']['Compression'])
print(conf['topsecret.server.com']['ForwardX11'])
print(conf['bitbucket.org'])
for key in conf['bitbucket.org']:
print(key)
print(conf.options('bitbucket.org'))
print(conf.items('bitbucket.org'))
print(conf.get('bitbucket.org', 'compression'))
2.2 增删改
import configparser
config = configparser.ConfigParser()
config.read('example.ini')
config.add_section('yuan')
config.remove_section('bitbucket.org')
config.set('yuan', 'k4', '323')
config.remove_option('topsecret.server.com', "forwardx11")
config.set('topsecret.server.com', 'host port', '2223')
config.write(open('new2.ini', "w"))