Using a config.ini file: Part 3 - Python lists as config.ini options.

I was in the middle of developing a small-time application. For me, it was to learn recursion, os.walk,  working with files..etc. The application I wrote was an incremental backup system, it scanned the directories supplied and backed up data changed from the last backup date stamp.

One of the challenges I came across, how to store the directories we want to scan, in this configuration file. If my loadConfig() function had not been modified, and i supplied multiple options, overwriting issues would happen.

So i modified both the loadConfig() and the saveConfig() functions to allow multi-named options and put those into a list rather than a direct string.

def loadConfig(fileLoc, folders=True):
    """ Loads configuration ini files. """
    import ConfigParser
    config = {}
    cp = ConfigParser.ConfigParser()
    cp.optionxform = str
    cp.read(fileLoc)
    for sec in cp.sections():
        if sec not in config:
            config[sec] = {}
        for opt in cp.options(sec):
            if sec != 'data':
                if opt not in config[sec]:
                    config[sec][opt] = {}
                config[sec][opt] = cp.get(sec, opt)
            else:
                if 'folders' not in config[sec]:
                    config[sec]['folders'] = []
                if opt.startswith('folder_'):
                    config[sec]['folders'].append(cp.get(sec, opt))
    return config

def saveConfig(fileLoc, config):
    """ Saves the configuration ini file. """
    import ConfigParser
    cp = ConfigParser.ConfigParser()
    cp.optionxform = str
    cfg = open(fileLoc, 'w')
    for sec in config:
        cp.add_section(sec)
        for opt in config[sec]:
            if sec == 'data':
                if opt == 'folders':
                    i=0
                    for options in config[sec][opt]:
                        cp.set('data','folder_{}'.format(str(i)), options)
                        i+=1
            else:
                cp.set(sec, opt, config[sec][opt])
    cp.write(cfg)
    cfg.close()
    return config

 

Print