[python 2.7.5] 实现配置文件的读写

 1 import ConfigParser
 2 
 3 config = ConfigParser.RawConfigParser()
 4 
 5 # When adding sections or items, add them in the reverse order of
 6 # how you want them to be displayed in the actual file.
 7 # In addition, please note that using RawConfigParser's and the raw
 8 # mode of ConfigParser's respective set functions, you can assign
 9 # non-string values to keys internally, but will receive an error
10 # when attempting to write to a file or when you get it in non-raw
11 # mode. SafeConfigParser does not allow such assignments to take place.
12 config.add_section('Section1')
13 config.set('Section1', 'an_int', '15')
14 config.set('Section1', 'a_bool', 'true')
15 config.set('Section1', 'a_float', '3.1415')
16 config.set('Section1', 'baz', 'fun')
17 config.set('Section1', 'bar', 'Python')
18 config.set('Section1', 'foo', '%(bar)s is %(baz)s!')
19 
20 # Writing our configuration file to 'example.cfg'
21 with open('example.cfg', 'wb') as configfile:
22     config.write(configfile)
23 
24 config.read('example.cfg')
25 
26 # getfloat() raises an exception if the value is not a float
27 # getint() and getboolean() also do this for their respective types
28 a_float = config.getfloat('Section1', 'a_float')
29 an_int = config.getint('Section1', 'an_int')
30 print a_float + an_int
31 
32 # Notice that the next output does not interpolate '%(bar)s' or '%(baz)s'.
33 # This is because we are using a RawConfigParser().
34 if config.getboolean('Section1', 'a_bool'):
35     print config.get('Section1', 'foo')
36 
37 config = ConfigParser.ConfigParser()
38 config.read('example.cfg')
39 
40 # Set the third, optional argument of get to 1 if you wish to use raw mode.
41 print config.get('Section1', 'foo', 0) # -> "Python is fun!"
42 print config.get('Section1', 'foo', 1) # -> "%(bar)s is %(baz)s!"
43 
44 # The optional fourth argument is a dict with members that will take
45 # precedence in interpolation.
46 print config.get('Section1', 'foo', 0, {'bar': 'Documentation',
47                                         'baz': 'evil'})

 

posted on 2013-10-01 18:03 kernel_main 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/kernel0815/p/3348664.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值