python小白-day6 ConfigParser模块

ConfigParser模块

用于生成和修改常见配置文档,当前模块的名称在 python 3.x 版本中变更为 configparser。

来看一个好多软件的常见文档格式如下

866894-20160223203237568-1972769099.png

用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' ))

866894-20160223203238036-328152290.png

增加hetan:

1
2
3
4
5
6
7
8
import configparser
 
config = configparser.ConfigParser()
config.read( 'example.ini' )
config.has_section( 'hetan' )
config.add_section( 'hetan' )
config[ 'hetan' ][ 'age' ] = "26"
config.write( open ( 'example.cfg' , 'w' ))

866894-20160223203238505-774653043.png

修改hetan中的age为25:

1
2
3
4
5
6
import configparser
 
config = configparser.ConfigParser()
config.read( 'example.cfg' )
config. set ( 'hetan' , 'age' , '25' )
config.write( open ( 'example.cfg.bak' , 'w' ))

866894-20160223203238865-202324649.png

删除hetan中的age:

1
2
3
4
5
6
import configparser
 
config = configparser.ConfigParser()
config.read( 'example.cfg.bak' )
config.remove_option( 'hetan' , 'age' )
config.write( open ( 'example.cfg.bak2' , 'w' ))

866894-20160223203239224-1354742810.png





转载于:https://www.cnblogs.com/hetan/p/5211133.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值