Using a config.ini file: Part 1 - Storing data.

def loadConfig(iniFile='config.ini'):
    """
    returns a dictionary with keys of the form
    config[section][options] = value
    """
    from ConfigParser import ConfigParser
    config = {}
    cp = ConfigParser()
    cp.optionxform = str
    cp.read(iniFile)
    for sec in cp.sections():
        if sec not in config:
            config[sec] = {}
        for opt in cp.options(sec):
            if opt not in config[sec]:
                config[sec][opt] = {}
            config[sec][opt] = cp.get(sec, opt)
    return config

So what I have here is, a simple function that opens a file and reads it's sections, options, and values inside.

A sample config.ini might look like

[sql]
hostname = 127.0.0.1
username = sa
password = mySAPassword
database = Application2

[settings]
defaultName = Joe Black

[smtp]
host = cmp-exch-1
port = 25
username = joebob
password = passdw1

So, we have a config.ini file and our new function. To use them in our Python application, we simply call

config = loadConfig('config.ini')

Now, the config variable (a dict) contains all of the sections, options, and values from the config.ini file.

print config['smtp']['host']
>> cmp-exch-1
print config['sql']['password'] 
>> mySAPassword

In another post, i will talk about writing a configuration file along with dealing with multiple same-named options in the config file. For example one application i wrote was a backup program, and we wanted to list all the folders the user wanted to be backed-up, in my config.ini file i wanted to be able to do:

folder = c:\usersowner\
folder = C:\applicationbackmeup\

But with the function above, this is impossible as the option folder would overwrite the previous one, leaving me with only one folder to backup.

Update 2013-05-11:

I have a slightly updated version of this function. With the current system all values are of type str so if you attempted to use them in an if statement like i did, for a True/False switch I was having to use == '1' to determine True and == '0' for False. It now converts 1, 0, True and False into it's respective Boolean type.

def loadConfig(fileLoc):
    """Loads configuration ini files."""
    import ConfigParser
    file_path = os.path.dirname(os.path.abspath(sys.argv[0]))
    config = {}
    cp = ConfigParser.ConfigParser()
    cp.optionxform = str
    cp.read(os.path.join(file_path, fileLoc))
    for sec in cp.sections():
        if sec not in config:
            config[sec] = {}
        for opt in cp.options(sec):
            if opt not in config[sec]:
                config[sec][opt] = {}
            data = cp.get(sec, opt)
            if data in ['True', '1']:
                data = True
            elif data in ['False', '0']:
                data = False
            config[sec][opt] = data
    return config

 

Print