Welcome to our third instalment of interesting Python modules. Unfortunately I’m a bit late with this section this week – in fact its next week already! The fourth instalment should be along towards the end of the week thus catching me up.
Today we’re going to cover something which isn’t in the standard library, but is nonetheless very useful. The module is configobj which is used for reading from and writing to INI style configuration files files. A simple INI file is shown below:
item1 = value
item2 = value2
[ section1 ]
item1 = value
[[ subsection ]]
item1 = value
In the above we can see the simple use of items, values sections and subsection. Subsections can be nested down as far a you want, but I don’t think most applications will need many more than two or three levels.
Installation
As this module isn’t in the standard library, we need to install it. On most Linux distros it should be in the package repositories, for example on Fedora 14:
$ sudo yum install python-configobj
Windows and Mac users can install from PyPi by following the instructions on the homepage.
Basic Usage
Reading from a configuration file with configobj couldn’t really be any simpler:
import configobj
config = configob.ConfigObj(filename)
myoption = config['item1']
mysectionoption = config['section1']['item1']
mysubsectionoption = config['section1']['subsection']['item1']
Basically, all you need to do is open a ConfigObj object by passing it a filename, then you just read from it as if its a dictionary object. Sections and subsections appear as nested dictionaries. Writing to the file is just as simple:
import configobj
config = configob.ConfigObj(filename)
config['newoption'] = 'new stuff'
config.write()
No surprises here, you just write to it as if it were a dictionary. All you have to do it call the write() method when you’ve finished, in order to sync everything to disk.
That’s pretty much it for basic usage. There is much more you can do with configobj, including advanced stuff like validation of configuration files. Check out the documentation for more info.
Leave a Reply