ConfigParser在3.0中已经重命名为configparser。
这个模块定义了ConfigParser类。该类实现了基本的配置文件解析器语言,类似于Microsoft Windows INI文件。不过不支持windows注册表的类型。
更强大的ini第3方模块参见:configobj。更多配置相关的模块,参见:%3Aaction=search&term=config&submit=search
准备文件:sample.ini
[book]
title: The Python Standard Library
author: Fredrik Lundh
email: fredrik@pythonware.com
version: 2.0-001115
[ematter]
pages: 250
[hardcopy]
pages: 350
代码1
#!/usr/bin/env python
# -*- coding: gbk -*-
#gtalk: ouyangchongwu#gmail.com
#python qq group: 深圳自动化测试python 113938272
import sys
#设定字符编码为GBK
reload(sys)
sys.setdefaultencoding('gbk')
import ConfigParser
import string
config = ConfigParser.ConfigParser()
config.read("sample.ini")
# print summary
print
print string.upper(config.get("book", "title"))
print "by", config.get("book", "author"),
print "(" + config.get("book", "email") + ")"
print
print config.get("ematter", "pages"), "pages"
print
# dump entire config file
for section in config.sections():
print section
for option in config.options(section):
print " ", option, "=", config.get(section, option):
输出结果:
THE PYTHON STANDARD LIBRARY
by Fredrik Lundh (fredrik@pythonware.com)
250 pages
book
title = The Python Standard Library
author = Fredrik Lundh
email = fredrik@pythonware.com
version = 2.0-001115
ematter
pages = 250
hardcopy
pages = 350
代码2:
#!/usr/bin/env python
# -*- coding: gbk -*-
#gtalk: ouyangchongwu#gmail.com
#python qq group: 深圳自动化测试python 113938272
import sys
#设定字符编码为GBK
reload(sys)
sys.setdefaultencoding('gbk')
import ConfigParser
import sys
config = ConfigParser.ConfigParser()
# set a number of parameters
config.add_section("book")
config.set("book", "title", "the python standard library")
config.set("book", "author", "fredrik lundh")
config.add_section("ematter")
config.set("ematter", "pages", 250)
# write to screen
config.write(sys.stdout)
输出结果:
[book]
title = the python standard library
author = fredrik lundh
[ematter]
pages = 250