May 2001
Intermediate to advanced
304 pages
6h 12m
English
The ConfigParser module reads configuration files.
The files should be written in a format similar to Windows INI files. The file contains one or more sections, separated by section names written in brackets. Each section can contain one or more configuration items.
Here’s the sample file used in 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
Example 5-16 uses the ConfigParser module to read the sample configuration file.
Example 5-16. Using the ConfigParser Module
File: configparser-example-1.py
import ConfigParser
import string
config = ConfigParser.ConfigParser()
config.read("samples/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
email = fredrik@pythonware.com
author = Fredrik Lundh
version = 2.0-001115
_ _name_ _ = book
ematter
_ _name_ _ = ematter
pages = 250
hardcopy
_ _name_ _ = hardcopy
pages = 350In Python 2.0, the ConfigParser module also allows you to write configuration ...
Read now
Unlock full access