# Read the config file config = eval(open('cfg.py').read()) # Use it like any other dict config['Hello'] = 'Modified World' # Write the changed config file back lines = [' {!r}: {!r},'.format(k, config[k]) for k in sorted(config)] open('cfg.py', 'w').write('\n'.join(['# Modified config', '{']+lines+['}'])) # Sample cfg.py { 'Hello': 'World', 'entry 1': 'This is a simple configuration file', 'entry 2': 'loader and writer for python.', 'entry 3': 'It can read and write any object that', 'entry 4': 'can be reproduced with repr().', 'sample dict': {'key': 'nested dict', 'purpose': 'test'}, 'sample list': [3.14, 'mixed list', 3000], 'sample tuple': ('foo', 'bar', 123), }