python ConfigParser模块

ConfigParser模块

https://docs.python.org/2/library/configparser.html

用法超简单
构造一个ConfigParser对象,然后read就行了,可以读多个文件。然后用一系列方法来取参数,

  • config.get
  • config.getint
  • config.getfloat
  • config.getboolean
import ConfigParser, os

config = ConfigParser.ConfigParser()
config.readfp(open('defaults.cfg'))
config.read(['site.cfg', os.path.expanduser('~/.myapp.cfg')])

如果要写的话用RawConfigParser,官方网站也有一个很好的例子:

import ConfigParser

config = ConfigParser.RawConfigParser()

# When adding sections or items, add them in the reverse order of
# how you want them to be displayed in the actual file.
# In addition, please note that using RawConfigParser's and the raw
# mode of ConfigParser's respective set functions, you can assign
# non-string values to keys internally, but will receive an error
# when attempting to write to a file or when you get it in non-raw
# mode. SafeConfigParser does not allow such assignments to take place.
config.add_section('Section1')
config.set('Section1', 'an_int', '15')
config.set('Section1', 'a_bool', 'true')
config.set('Section1', 'a_float', '3.1415')
config.set('Section1', 'baz', 'fun')
config.set('Section1', 'bar', 'Python')
config.set('Section1', 'foo', '%(bar)s is %(baz)s!')

# Writing our configuration file to 'example.cfg'
with open('example.cfg', 'wb') as configfile:
    config.write(configfile)
阅读更多
个人分类: python
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭