| Line | |
|---|
| 1 | How to use ConfigParser |
|---|
| 2 | ======================= |
|---|
| 3 | How 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 | |
|---|
| 12 | First 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 | |
|---|
| 29 | The content is then readable by a ConfigParser instance:: |
|---|
| 30 | |
|---|
| 31 | >>> from ConfigParser import ConfigParser |
|---|
| 32 | >>> config = ConfigParser() |
|---|
| 33 | >>> read = config.read([filename]) |
|---|
| 34 | |
|---|
| 35 | We 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 | |
|---|