zoukankan      html  css  js  c++  java
  • [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'})
  • 相关阅读:
    idea打包jar部署Linux出现乱码
    HTML元素刷新方式
    Linux中Jar启动与停止
    Win10开机自启软件设置
    java后台数据传输到前端少一天,8小时
    mysql字符串提取数组排序
    maven 配置文件
    mac docker安装jupyter notebook镜像
    pycharm使用git
    github使用命令
  • 原文地址:https://www.cnblogs.com/kernel0815/p/3348664.html
Copyright © 2011-2022 走看看