1

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'}}

3 Answers 3

4

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'}}
Sign up to request clarification or add additional context in comments.

Comments

0

Have a look at configparser from the standard library

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.