Mark Harrison
Mark Harrison

Reputation: 304434

Python: Parsing INI-style configuration files?

How can I parse an INI-style configuration file using Python? Is there a standard module that can be used?

[section1]
n = 1

[section2]
s = foo

Ideally I would get a two-level dictionary like this:

>>> config
{'section2': {'s': 'foo'}, 'section1': {'n': '1'}}

Upvotes: 1

Views: 298

Answers (3)

Darin
Darin

Reputation: 508

I wrote a simple class to read/write from INI files. You can replace the "odict" bits with regular dictionaries if you don't want to rely on an external library. Note: this code was tested for python 2.7.

from collections import OrderedDict as odict
import sys

class IniFile(object):
    def __init__(self,fn=None):
        self.fn = fn
        self.top = odict()
        self.sections = odict()
        if fn: self.read()
    def read(self,fn=None):
        fn = fn or self.fn
        assert fn
        handle = open(fn)
        current = self.top
        for line in handle.readlines():
            try:
                stripped = line.strip()
                if stripped.startswith(";"): continue
                if "#" in stripped:
                    where = stripped.find("#")
                    if where == 0: continue
                    stripped = stripped[0:where]
                if "=" in stripped:
                    k,v = stripped.split("=",1)
                    current[k.strip()] = v.strip()
                elif stripped.startswith("[") and stripped.endswith("]"):
                    inside = stripped[1:-1]
                    current = self.sections.setdefault(inside,odict())
            except Exception,e:
                print >>sys.stderr,"problem with:"
                print >>sys.stderr,line
                raise
        handle.close()
    def write(self,fn=None):
        if fn is None: fn = self.fn
        if fn is None: raise Exception("please specify a filename!")
        handle = open(fn,"w")
        for key,value in self.top.items():
            handle.write("%s=%s\n" % (key,value))
            handle.flush()
        for name,content in self.sections.items():
            handle.write("[%s]\n" % name)
            handle.flush()
            for key,value in content.items():
                handle.write("%s=%s\n" % (key,value))
                handle.flush()
        handle.close()
        return fn

Upvotes: 0

ron rothman
ron rothman

Reputation: 18128

With ConfigParser (configparser in Python3) as the foundation,

from ConfigParser import ConfigParser

config = ConfigParser()
config.read('config.ini')

print config.sections()
# ['section1', 'section2']

print config.items('section2')
# [('s', 'foo')]

you could build your dict-like structure like this:

config_dict = {}

for section in config.sections():
    config_dict[section] = dict(config.items(section))

print config_dict
# {'section2': {'s': 'foo'}, 'section1': {'n': '1'}}

Upvotes: 4

Florian Diesch
Florian Diesch

Reputation: 1025

Have a look at configparser from the standard library

Upvotes: 0

Related Questions