Reading INI Configuration Files

Credit: Dirk Holtwick


You want to load a configuration file for your program, but you don’t want to use a Python module for this purpose, as that might expose you to security risks or troublesome syntax and other errors in the module.


The standard ConfigParser library module gives us almost all we need to use INI files for configuration:

import ConfigParser
import string

_ConfigDefault = {
    "database.dbms":            "mysql",
    "":            "",
    "database.user":            "root",
    "database.password":        "",
    "":            ""

def LoadConfig(file, config={}):
    returns a dictionary with keys of the form
    <section>.<option> and the corresponding values
    config = config.copy(  )
    cp = ConfigParser.ConfigParser(  )
    for sec in cp.sections(  ):
        name = string.lower(sec)
        for opt in cp.options(sec):
            config[name + "." + string.lower(opt)] = string.strip(
                cp.get(sec, opt))
    return config

if _ _name_ _=="_ _main_ _":
    print LoadConfig("some.ini", _ConfigDefault)


Many people use Python modules as configuration files, but this may allow your program to be manipulated or let a syntax error come into that file. To use INI-style configuration files, which are known from Windows (but can also be used under Unix-like systems, since they’re just text files with some structure), try the small script here.

The code in the recipe is just for reading configuration files, but writing them is also easy to implement. An INI file looks like this:

user = dummy
password = tosca123

You can set the defaults in advance. Note that the keys of the dictionary are always lowercase.

See Also

Documentation for the ConfigParser module in the Library Reference.

Get Python Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.