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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.