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