configparser模块-配置文件格式
configparser模块
该模块用于配置文件的格式,与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。
创建文件
import configparser config = configparser.ConfigParser() config["DEFAULT"] = {'ServerAliveInterval': '45', 'Compression': 'yes', 'CompressionLevel': '9', 'ForwardX11':'yes' } config['bitbucket.org'] = {'User':'hg'} config['topsecret.server.com'] = {'Host Port':'50022',
'ForwardX11':'no'} with open('example.ini', 'w') as configfile: config.write(configfile)
查找文件
import configparser config = configparser.ConfigParser() config.read('example.ini')
#查找文件内容,基于字典的形式,先读取才能查看
print(config.sections()) #['bitbucket.org', 'topsecret.server.com']#不会显示default节里面的配置内容
print('bytebong.com' in config) # False
print('bitbucket.org' in config) # True
print(config['bitbucket.org']["user"]) # hg 查看section中对应键的值
print(config['topsecret.server.com']['ForwardX11']) #no
print(config['bitbucket.org']) #<Section: bitbucket.org>
for key in config['bitbucket.org']: # 对节做循环,输出对应节中的键,如果有default节,则default节中的键也会输出
print(key)
print(config.options('bitbucket.org')) #同for循环一样,找到'bitbucket.org'节下所有键,包括default节中的键
print(config.items('bitbucket.org')) #找到'bitbucket.org'节下所有键值对
print(config.get('bitbucket.org','compression')) # yes get方法获取Section下的key对应的valu
增删改操
import configparser config = configparser.ConfigParser() config.read('example.ini') config.add_section('kinds')#增加新section 节 ‘kinds’ config.set('kinds','fruit','apple')#在节中添加键值对 config.set('bitbucket.org','user','hello')#修改键值 config.remove_section('bitbucket.org')#删除节 config.remove_option('topsecret.server.com',"forwardx11")#删除节下对应的键 config.write(open('new_config','w'))#新建文件并存储 说明:配置文件时,对节的增删改查都需先read()