Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Reading INI Configuration Files

Credit: Dirk Holtwick

Problem

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.

Solution

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.name":            "",
    "database.user":            "root",
    "database.password":        "",
    "database.host":            "127.0.0.1"
    }

def LoadConfig(file, config={}):
    """
    returns a dictionary with keys of the form
    <section>.<option> and the corresponding values
    """
    config = config.copy(  )
    cp = ConfigParser.ConfigParser(  )
    cp.read(file)
    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)

Discussion

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:

[database] ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata