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

每一次的操作都是對文件的重新寫入生成

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章