ConfigParser模块
用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。
来看一个好多软件的常见文档格式如下
用python生成上文档代码如下;
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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) |
读文档:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | >>> import configparser >>> config = configparser.ConfigParser() >>> config.sections() [] >>> config.read( 'example.ini' ) [ 'example.ini' ] >>> config.sections() [ 'bitbucket.org' , 'topsecret.server.com' ] >>> 'bitbucket.org' in config True >>> 'bytebong.com' in config False >>> config[ 'bitbucket.org' ][ 'User' ] 'hg' >>> config[ 'DEFAULT' ][ 'Compression' ] 'yes' >>> topsecret = config[ 'topsecret.server.com' ] >>> topsecret[ 'ForwardX11' ] 'no' >>> topsecret[ 'Port' ] '50022' >>> for key in config[ 'bitbucket.org' ]: print (key) ... user compressionlevel serveraliveinterval compression forwardx11 >>> config[ 'bitbucket.org' ][ 'ForwardX11' ] 'yes' |
删除bitbucket.org:
1 2 3 4 5 6 | import configparser config = configparser.ConfigParser() config.read( 'example.ini' ) config.remove_section( 'bitbucket.org' ) config.write( open ( 'example.bak' , 'w' )) |