ConfigParser模块用于读取配置文件。
配置文件的格式与Windows INI 文件类似,可以包含一个或多个区域(section),每个区域可以有多个配置条目。
这里有个样例配置文件sample.ini, 在 Example 5-16 用到了这个文件:
[book]
title: The Python Standard Library
author: Fredrik Lundh
email: fredrik@pythonware.com
version: 2.0-001115
[ematter]
pages: 250
[hardcopy]
pages: 350
1、 Example 5-16. 使用 ConfigParser 模块
import ConfigParser
import string
config = ConfigParser.ConfigParser()
config.read("sample.ini")
for section in config.sections():
print section
for option in config.options(section):
print " ", option, "=", config.get(section, option)
#结果
book
title = The Python Standard Library
author = Fredrik Lundh
email = fredrik@pythonware.com
version = 2.0-001115
ematter
pages = 250
hardcopy
pages = 350
2、 Example 5-17. 使用 ConfigParser 模块写入配置数据
File: configparser-example-2.py
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