Python的configparser生成配置文件,以及相关操作

Python中使用configparser生成配置文件,如下

import configparser
 
config = configparser.ConfigParser()
 
config["DEFAULT"] = {'ServerAliveInterval':30,
                     'Compression':'no',
                     'CompressionLevel':'7'}
config['bitbucket.org']={}
config['bitbucket.org']['User'] = 'ljj'
config['www.server.com']={}
config['baseInfo'] = {
    'BaseUrl':'test.baidu.com',
    'Port':8080
}
topsecret = config['www.server.com']
topsecret['Host Port'] = '8088'
topsecret['ForwardX11'] = 'no'
config['DEFAULT']['ForwardX11'] = 'yes'
 
with open('example.ini','w') as configfile:
    config.write(configfile)
 
config.read('example.ini')
print(config.sections())#读取配置文件
print(config.defaults())#读取默认的default
print(config['www.server.com']['host port'])
# 循环取出key,包括default的key值
for key in config['bitbucket.org']:
    print(key)
config.remove_section('www.server.com')
config.write(open('example.ini','w'))
print(config.has_section('www.server.com'))
config.set('bitbucket.org','user','ls')#设置键下面的键值对
config.write(open('example.ini','w'))
config.remove_option('bitbucket.org','user')#删除键下面的
config.write(open('example.ini','w'))

生成之后,生成文件example.ini

每一次的操作都是对文件的重新写入生成

posted @ 2019-09-25 10:58  测试的世界很精彩  阅读(1116)  评论(0编辑  收藏  举报