python之configparser模組(配置檔案)
阿新 • • 發佈:2018-12-26
該模組主要是針對於配置檔案的生成 以及生成後的增刪改查操作
第一步生成
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' # mutates the parser
topsecret['ForwardX11'] = 'no' # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
config.write(configfile)
執行以上程式碼則會生成一個 example.ini 配置檔案
查
# 查
config.read('example.ini')
content = config.sections()
print(config.defaults())
print(config['bitbucket.org']['user'])
for key in config['bitbucket.org']:
print(key)
結果如下
OrderedDict([('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes' )])
hg
user
serveraliveinterval
compression
compressionlevel
forwardx11
修改刪除
# 刪除
config.remove_section('topsecret.server.com')
config.remove_option('bitbucket.org','user')
# 修改
config.set('bitbucket.org','k1','11111')
config.write(open('example.ini', "w"))
最後一行程式碼必不可少 刪除和修改其實就是覆蓋的原理