My first post about using a config.ini file I had provided the function to load a configuration file into an easily used and accessed dict. One thing that I've recently run into, is the want/need to be able to write back to the file. I have the functions code listed below. So you've used the loadConfig() function to load the information into a variable. As such, the data can now be accessed as such:
config = loadConfig('config.ini') print config['settings']['users'] # OR and better way would be to use Python's # .get function which allows setting up default values print config['settings'].get('users', 'default,users,listing')
We've now reached the point in time when we want to write to the configuration file. Doing such, is as simple as:
config['settings']['lastSync'] = '2013-05-11' saveConfig(config, 'config.ini)
Essentially, we pass the dict back to the saveConfig() function which now contains our changed data, which is then rewritten to the file of our choice, config.ini as in our case here. The only thing i have noticed, is that since by default Python dict's order in a certain way, it may rearrange the sections, but everything will be there.
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]: cp.set(sec, opt, config[sec][opt]) cp.write(cfg) cfg.close() return config