1 - The configparser module 

The Python language has a module called configparser which allows you to use and manipulate configuration files similar to Windows files of .ini type. The configparser module can be used to manage user-configurable configuration files within an application. The content of a configuration file can be organized into sections containing each of the parameters with associated values. Several types of option values ​​are supported, including integers, floating point values, and booleans.

2 - Installation of the configparser module 

Nothing more simple to install the configparser module, just type on the command line:

 pip install config-parser

3 - Format of the configuration file 

The file format used by configparser is similar to that used by older versions of Microsoft Windows. It consists of one or more named sections, each of which may contain options with names and values.

  1. The configuration file sections are identified by looking for lines starting with '[' and ending with ' ] '. The value between the brackets indicates the name of the section and can contain all the characters except the brackets. 
  2. The options are listed one per line in a section. 
  3. The line starts with the name of the option, which is separated from the value by  ":" or an equal sign "=" 
  4. Comments: are lines starting with a semicolon ';' Or a hash " # " and are treated as comments and are not visible when accessing the contents of the configuration file. 
 

The following example in the configuration file has a section called settings with three options, host, username and password:

# Server configuration settings
[settings]
host : 127.0.0.1
username : root
password : root

4- Reading the value of an option from an .ini configuration file in Python

With the Python language we can use the configparser module and the read () method of the ConfigParser object to read the configuration file:

Example. Reading the configuration.ini file in Python

from configparser import ConfigParser
parser = ConfigParser ()
parser.read ('configuration.ini')

# Display the 'host' parameter value
print (parser.get ('settings', 'host'))
# The output is: 127.0.0.1

5 - Update the parameter of a section


To update a parameter in the configuration file, you must first open it in read and write mode and then use the set() method of the ConfigParser class.

Example. update the value of the parameter 'host'

from configparser import ConfigParser
parser = ConfigParser ()
parser.read ('configuration.ini')

# Open the configuration file in read and write mode
file = open ('configuration.ini', 'r+')

# update the value of the 'host' parameter
parser.set ('settings', 'host', 'localhost')
parser.write (file)
file.close ()

Now if you open the configuration.ini file, you will see that the parameter:
host = 127.0.0.1 
has become:
host = localhost

6 - Reading the sections of a configuration file 

The sections() method of the parser object allows you to retrieve the sections of the configuration file in object of a list type:

Example. configuration.ini

[settings]
# server configuration parameters
host : 127.0.0.1
username : root
password : root

[Safe_Mode]
# http://php.net/safe-mode
safe_mode = Off
safe_mode_gid = on

[File_Uploads]
# http://php.net/file-uploads
file_uploads = On
upload_tmp_dir = "c:/wamp/tmp"
upload_max_filesize = 20M

Example. reading sections of the configuration.ini file

from configparser import ConfigParser
parser = ConfigParser()
parser.read('configuration.ini')
sec = parser.sections()
print(sec)
# The output is: ['settings', 'Safe_Mode', 'File_Uploads']

7 - Read the list of options with the options() method


The options() method of the ConfigParser object allows you to retrieve the list options in a section of the configuration file:

Example. The list  options in the first section:

from configparser import ConfigParser
parser = ConfigParser()
parser.read ('configuration.ini')
# getting the first section
sec = parser.sections()[0]
# get the list of options
print (sec, parser.options(sec))
# The output is: settings ['host', 'username', 'password']

Now by using the for loop statement, we can get all sections with their options:

Example. List of all sections with their options: 

from configparser import ConfigParser
parser = ConfigParser()
parser.read('configuration.ini')

# Browse all sections
for sec in parser.sections():
# cycle through options in different sections
print (sec, ":", parser.options (sec))

The output is:
settings: ['host', 'username', 'password']
Safe_Mode: ['safe_mode', 'safe_mode_gid']
File_Uploads: ['file_uploads', 'upload_tmp_dir', 'upload_max_filesize']

8 - Total reading with the items() method 

The items() method allows you to retrieve the names of the parameters with their values:

Example. retrieving the parameters and values ​​from the first section

from configparser import ConfigParser
parser = ConfigParser ()
parser.read ('configuration.ini')

# Point to the first section
sec = parser.sections()[0]
print (sec, ":")
for name, value in parser.items(sec):
print(name, value)

Full display of sections with their parameters and values:

from configparser import ConfigParser
parser = ConfigParser ()
parser.read ('configuration.ini')

# Browse sections
for sec in parser.sections ():
print (sec, ":")
# browse parameters and values
for name, value in parser.items (sec):
print(name, value)

The output is:

settings:
host = 127.0.0.1
username = root
password = root
Safe_Mode:
safe_mode = Off
safe_mode_gid = on
File_Uploads:
file_uploads = On
upload_tmp_dir = "c:/wamp/tmp"
upload_max_filesize = 20M

9 - Adding a section with the add_section() method 

 With the add_section() method of the ConfigParser class, you can add as many sections as you want, for that you must first open the configuration file in read and write mode and then use the set () method of the ConfigParser class  to be able to define and add new options to the section.

Example. Adding a section named mysqld

from configparser import ConfigParser
parser = ConfigParser()
parser.read ('configuration.ini')

# Opening the configuration file
file = open('configuration.ini', 'r+')

# Adding a new mysqld section
parser.add_section ('mysqld')
# Definition and addition of new options
parser.set('mysqld', 'port', '3306')
parser.set('mysqld', 'table_cache', '64')
parser.write(file)
file.close()

After executing the code, you will see a new section [mysqld] which is added to the configuration.ini file:


[settings]
host = 127.0.0.1
username = root
password = root

[Safe_Mode]
safe_mode = Off
safe_mode_gid = on

[File_Uploads]
file_uploads = On
upload_tmp_dir = "c:/wamp/tmp"
upload_max_filesize = 20M

[mysqld]
port = 3306
table_cache = 64

 Younes Derfoufi
my-courses.net

Leave a Reply