How To Use Python ConfigParser To Read Write Configuration File

Configuration file in python is a text file which contains section and seciton’s options. The file extension is .ini. This is same with windows .ini file. One configuration file can contains multiple sections. And python configparser.ConfigParser class provide methods to read, write, update and remove the .ini file content. This article will show you some examples.

1. Python Configuration File Example.

Below content contains two section, the section name begins with [ and ends with ]. The options are saved in key value pair format.

[mysql_conn_data]
host=localhost
database=dev2qa

[account]
user_name=jerry
password=888888

2. Read Configuration File.

2.1 Read Single Configuration File.

Support we save above configuration data in file /home/jerry/config_file_1.ini. Then we can use ConfigParser class’s get(section_name, option_key) method to get related option value.

# import ConfigParser class.
>>> from configparser import ConfigParser

# create an instance of ConfigParser class.
>>> parser = ConfigParser()

# read and parse the configuration file.
>>> parser.read('/home/jerry/config_file_1.ini')
['/home/jerry/config_file_1.ini']

# get option value in specified section.
>>> mysql_conn_host = parser.get('mysql_conn', 'host')

# print the option value.
>>> print(mysql_conn_host)
localhost

>>> account = parser.get('account', 'user_name') 
>>> 
>>> print(account) 
jerry

2.2 Read Multiple Configuration File.

Now we will create another configuration file /home/jerry/config_file_2.ini with below content. Below configuration file also cotains a [account] section which is same with config_file_1.ini.

[oracle_conn_data]
host=2.2.2.2
database=orcl

[account]
user_name=orcl
password=orcl888

Run below python source code. You will find the second config file [account] section data will be used because of same section name with config file 1.

>>> from configparser import ConfigParser
>>> 
>>> parser = ConfigParser()
>>> 
# add the two configuration file in a list object.
>>> config_file_list = ['/home/jerry/config_file_1.ini', '/home/jerry/config_file_2.ini']
>>> 
# read above list object to parse the two configuration files.
>>> parser.read(config_file_list)
['/home/jerry/config_file_1.ini', '/home/jerry/config_file_2.ini']
>>> 
>>> oracle_conn_host = parser.get('oracle_conn', 'host')
>>> 
>>> print(oracle_conn_host)
2.2.2.2
>>> 
# the second configuration file's section will override the first configuration file same section value.
>>> account = parser.get('account', 'user_name')
>>> 
>>> print(account)
orcl

3. Configuration File Sections And Options Operation Method.

3.1 sections(), options(section_name) and items(section_name) method.

The ConfigParser class provide sections(), options(section_name) and items(section_name) method to get all config file sections and options value. If multiple configure file contains same section name, then the second configure file’s section’s options will be used.

>>> from configparser import ConfigParser
>>> 
>>> parser = ConfigParser()
>>> 
>>> config_file_list = ['/home/jerry/config_file_1.ini', '/home/jerry/config_file_2.ini']
>>> 
>>> parser.read(config_file_list)
['/home/jerry/config_file_1.ini', '/home/jerry/config_file_2.ini']
>>>

# get all sections. 
>>> for section in parser.sections():
           
        # get current section's options.
...     options = parser.options(section)
...     print('Section', section, ' has ', options, ' options.')

        # get option's key and value item. 
...     for key, value in parser.items(section):
...         print(key, ' = ', value)
... 

Section mysql_conn  has  ['host', 'database']  options.
host  =  localhost
database  =  dev2qa

Section account  has  ['user_name', 'password']  options.
user_name  =  orcl
password  =  orcl888

Section oracle_conn  has  ['host', 'database']  options.
host  =  2.2.2.2
database  =  orcl

3.2 has_section(section_name), has_option(section_name, option_name) method.

These two method will check whether the provided section, or option exist ot not.

>>> parser.has_section('mysql_conn')
True

>>> parser.has_option('mysql_conn', 'port')
False

4. Modify Configuration File Section And Option Values.

4.1 Add Section And Options Then Write To File.

Please remember invoke file.close() method to save new configuration items to the target file at the coding end. Otherwise the file content will be empty.

# add a new section.
>>> parser.add_section('hello')

# add a new option in above section.
>>> parser.set('hello', 'username', 'tom')

# open a configuration file
>>> file = open('/home/jerry/config_file_1.ini')

# write the new section and options to the file.
>>> parser.write(file)

# do not forget close the file to flush the parser sections.
>>> file.close()

# you can also write the parser sections to system console to verify the section and option values.

# do not forget import sys module, otherwise you will encounter NameError: name 'sys' is not defined
>>> import sys

>>> parser.write(sys.stdout)

[mysql_conn]
host = localhost
database = dev2qa

[account]
user_name = orcl
password = orcl888

[oracle_conn]
host = 2.2.2.2
database = orcl

[hello]
username = tom

4.2 Edit Section And Option Values.

Use ConfigParser’s set(section_name, option_name, option_value) method to set section and option values.

>>> parser.set('account', 'user_name', 'test')
>>> 
>>> parser.write(sys.stdout)
[mysql_conn]
host = localhost
database = dev2qa

[account]
user_name = test
password = orcl888

[oracle_conn]
host = 2.2.2.2
database = orcl

[hello]
username = tom

4.3 Remove Section And Options.

ConfigParser’s remove_section(section_name), remove_option(section_name, option_name) method will remove section and options.

# remove [hello] section.
>>> parser.remove_section('hello')
True

# remove 'password' option in [account] section.
>>> parser.remove_option('account', 'password')
True

# check whether the remove action success or not.
>>> parser.write(sys.stdout)
[mysql_conn]
host = localhost
database = dev2qa

[account]
user_name = test

[oracle_conn]
host = 2.2.2.2
database = orcl

1 thought on “How To Use Python ConfigParser To Read Write Configuration File”

  1. In section 4.1 you probably need to change:

    file = open(‘/home/jerry/config_file_1.ini’)

    to:

    file = open(‘/home/jerry/config_file_1.ini’, mode=’w’)

    Otherwise, the following error may appear:

    UnsupportedOperation: not writable

Leave a Comment

Your email address will not be published. Required fields are marked *

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