Configparser module-how to red and write in configuration.ini

 

1. The configparser module

Python’s configparser module is a powerful and versatile library designed to handle configuration files in various formats. It provides a flexible and intuitive way to read, write, and manipulate configuration files for Python applications.
The configparser module allows developers to define and parse configuration files using a simple syntax. It supports three different types of configuration files: .INI, which is the most commonly used format; an extended INI format that includes features such as multiline values and interpolation; and the older ConfigParser format.
With configparser, you can easily create, modify, and access sections and options within a configuration file. It enables you to organize your settings into logical sections, making it easier to manage and maintain complex configurations. Sections can have multiple key-value pairs, referred to as options, which store the actual configuration data.

2. Installation of the configparser module

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

pip install config-parser

pip install configparser module

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.

configparser module: options values

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

10. Methods associated with the configparser module

The configparser module in Python provides several methods to work with configuration files. Here is a list of some of the commonly used methods associated with configparser:

  1. ConfigParser(): This is the constructor method that creates a new configparser object.
  2. read(filename): Reads the configuration data from the specified file.
  3. read_file(f): Reads the configuration data from a file-like object.
  4. read_string(string): Reads the configuration data from a string.
  5. sections(): Returns a list of all sections in the configuration file.
  6. has_section(section): Checks if the specified section exists in the configuration file.
  7. options(section): Returns a list of all options within a section.
  8. has_option(section, option): Checks if the specified option exists within a section.
  9. get(section, option): Retrieves the value of an option within a section.
  10. getint(section, option): Retrieves the value of an option as an integer.
  11. getfloat(section, option): Retrieves the value of an option as a float.
  12. getboolean(section, option): Retrieves the value of an option as a boolean.
  13. set(section, option, value): Sets the value of an option within a section.
  14. add_section(section): Adds a new section to the configuration file.
  15. remove_section(section): Removes a section and all its options from the configuration file.
  16. remove_option(section, option): Removes a specific option from a section.
  17. write(fileobject): Writes the configuration data to the specified file object.
  18. write_file(f): Writes the configuration data to a file-like object.
  19. write_string(): Returns the configuration data as a string.

These are some of the key methods provided by the configparser module to perform various operations on configuration files in Python.

Leave a Reply