您的位置:首页 > 编程语言 > Python开发

Python模块之ConfigParser

2018-03-18 21:30 423 查看

ConfigParser模块

用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。常见文档格式如下:[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

[bitbucket.org]
User = hg

[topsecret.server.com]
Port = 50022
ForwardX11 = no用python生成一个这样的文档:import configparser #python3:cinfigparser;python2: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)

#读取
print(config.sections())
print(config.read('example.ini'))
print('bitbucket.org' in config)
print(config['bitbucket.org']['User'])
for key in config['bitbucket.org']:
print(key)
secs = config.sections()
options = config.options('group2')
item_list = config.items('group2')
val1 = config.get('group1','key')
val2 = config.getint('group1','key')
print(secs,options,item_list,val1,val2)
#改写
sec = config.remove_section('group1')
config.write(open('i.cfg', "w"))

sec = config.has_section('wupeiqi')
sec = config.add_section('wupeiqi')
config.write(open('i.cfg', "w"))

config.set('group2','k1',11111)
config.write(open('i.cfg', "w"))

config.remove_option('group2','age')
config.write(open('i.cfg', "w"))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: