root / PyCon07 / material / recipe_10.txt

Revision 57:efd3c5bd5313, 1.0 kB (checked in by Tarek Ziad?? <tarek@…>, 19 months ago)

more on recipes

Line 
1How to use ConfigParser
2=======================
3How to use ConfigParser
4=======================
5
6:abstract:
7
8    ConfigParser provides a high level access to ini files.
9    This recipe will show you how it can be used to provide
10    a programm a simple configuration access
11
12First of all, let's create a configuration file::
13
14    >>> config = """\
15    ... [webpages]
16    ... python=http://python.org
17    ... pycon=http://us.pycon.org
18    ...
19    ... [options]
20    ... path=/tmp
21    ... words=cool,fun,neat
22    ... """
23    >>> import os
24    >>> filename = os.path.join('/tmp', 'conf.ini')
25    >>> f = open(filename, 'w')
26    >>> f.write(config)
27    >>> f.close()
28
29The content is then readable by a ConfigParser instance::
30
31    >>> from ConfigParser import ConfigParser
32    >>> config = ConfigParser()
33    >>> read = config.read([filename])
34   
35We can then read the sections of the file with the `options` methods::
36
37    >>> res = config.items('options')
38    >>> res.sort()
39    >>> res
40    [('path', '/tmp'), ('words', 'cool,fun,neat')]
41
Note: See TracBrowser for help on using the browser.