configparser模块简介
该模块适用于配置文件的格式与windows ini文件类似,可以包含一个或多个节(section),每个节可以有多个参数(键=值)。节与java原先的配置文件相同的格式
看一下configparser生成的配置文件的格式
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
ForwardX11 = yes
[bitbucket.org]
User = Atlan
compression = yes
[topsecret.server.com]
Port = 50022
ForwardX11 = no
现在看一下类似上方的配置文件是如何生成的
import configparser
config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9',
'ForwardX11':'yes'
}
config['bitbucket.org'] = {'User':'Atlan'}
config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}
with open('example.ini', 'w') as configfile:
config.write(configfile)
解释一下,操作方式
config["DEFAULT"] = {'ServerAliveInterval': '45',
'Compression': 'yes',
'CompressionLevel': '9',
'ForwardX11':'yes'
}
config['bitbucket.org'] = {'User':'Atlan'}
和字典的操作方式相比,configparser模块的操作方式,无非是在实例化的对象后面,跟一个section,在紧跟着设置section的属性(类似字典的形式)
读文件内容
import configparser
config = configparser.ConfigParser()
print(config.sections())
config.read('example.ini')
print(config.sections())
print('bytebong.com' in config)
print('bitbucket.org' in config)
print(config['bitbucket.org']["user"])
print(config['DEFAULT']['Compression'])
print(config['topsecret.server.com']['ForwardX11'])
print(config['bitbucket.org'])
for key in config['bitbucket.org']:
print(key)
print(config.options('bitbucket.org'))
print(config.items('bitbucket.org'))
print(config.get('bitbucket.org','compression'))
修改
import configparser
config = configparser.ConfigParser()
config.read('example.ini')
config.add_section('yuan')
config.remove_section('bitbucket.org')
config.remove_option('topsecret.server.com',"forwardx11")
config.set('topsecret.server.com','k1','11111')
config.set('yuan','k2','22222')
with open('new2.ini','w') as f:
config.write(f)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)