Python – work with configuration files

Python language provides an out-of-the-box module to work with the configuration files.
The configparser module in Python 3, (it replaces the ConfigParser module of Python 2) defines the class ConfigParser that implements a basic configuration file parser language.
The structure of the configuration file is the following:

We can define different sections where each section contains a set of options. The syntax of each option is “optionName: optionValue“.
To get the value of each section and option programmatically we can use the following code. I tested it with Python 3.4.4.
Firstly I created a new configuration file named py_config.conf with this content (3 sections ad a bunch of options):

To get the configuration file reference we have just to create a new ConfigParser object and read the previously created file:

To display all the sections of the configuration file we can call the .sections() method. It returns a list of all the sections.


To display all the options within a given section we can use the .options() method. It takes the section name as parameter and returns all the option withing the given section.


The section name parameter is case sensitive so this will not work as expected.


Finally, to get an option value we can use the .get() method with the section and option name parameters.


The option name parameter is case insensitive so this will work fine (notice that the option name is different from the one defined in the config file).


Due to the case insensitivity of the option name, if our configuration file contains at least two options with the same option key within the same section,
the .read() method will throw a DuplicateOptionError exception.