config file in python

Save Configuration in Python

Python has “ConfigParser” module that allow you read or write configuration to “.ini” file.
And here is how to read or write to config file. First of all you need to create “.ini” file, for instance “hello.ini”

[main]
username = myusername
password = mypassword

Read config file:

from ConfigParser import SafeConfigParser

config = SafeConfigParser()
config.read('hello.ini')

db_user = config.get('main', 'username')
db_pass = config.get('main', 'password')

Write config file:

from ConfigParser import SafeConfigParser

config = SafeConfigParser()
config.read('hello.ini')
config.add_section('main')
config.set('main', 'username', 'mynewusername')
config.set('main', 'password', 'mynewpassword')
config.set('main', 'new_key', 'my new value')

with open('hello.ini', 'w') as f:
    config.write(f)

Reference: http://stackoverflow.com/a/19078712/1936697