ConfigParser - Reading And Writing Configuration Values In Python

Introduction to Configuration Files:

Configuration files are necessary for any industry standard software product.

Configurations files control any aspect of a software module.  

Examples of configurations include Look and Feel of the User Interface, Heartbeat intervals, Compression Ratios, Network speed selection, Database parameters and so on.

By having a configuration driven software product hard coding values such as threshold values are avoided. Configuration files help in avoiding recompilation of programs and make the debugging process lot easier.

Windows based software products use .ini file format and web servers like Apache use XML based configuration files.

The Python Standard Library comes with a ConfigParser class that helps in all the aspects of reading values from and writing updated configuration values to a configuration file.

The configuration file format supported by the Python ConfigParser class is very similar to the windows INI file format.


Configuration file format supported by ConfigParser:

  • The configuration file format supported by ConfigParser contains a section header and contains values for configuration entries under each section
  • Configuration entries are name value pairs separated by either a "colon" symbol or an "equal to" symbol
  • Comments can start with a hash "#" or a semi colon ":" .


Python ConfigParser Example - Reading Values from a Configuration File:

The following configuration file named "config.val" is read by the sample python program using a  ConfigParser object and values are printed.


primary color   = white

secondary color = green

initial state   = shown



heartbeat   = 2 seconds

speed       = dynamic


#import the configparser module

import configparser


#instantiate the ConfigParser class

config = configparser.ConfigParser()'./config.val')


#print section 1

print("=========>Section 1 values:%s<========="%(config.sections()[0]))

print(config['UI']['primary color'])

print(config['UI']['secondary color'])

print(config['UI']['initial state'])


#print section 2

print("=========>Section 2 values:%s<========="%(config.sections()[1]))







Output of Python Example, reading Values from a Configuration File:


=========>Section 1 values:UI<=========




=========>Section 2 values:Network<=========

2 seconds



Copyright 2018 ©