Read INI Files in Python: Step-by-Step Guide

In Python, you can use the configparser module to read and parse ini configuration files.

Firstly, you need to import the configparser module.

import configparser

Next, create a configparser object and use the read() method to read the ini configuration file.

config = configparser.ConfigParser()
config.read('config.ini')

Next, you can use the get() method to retrieve the value in the configuration file.Assuming there is a section named database in the ini configuration file, with an option named host, you can use the following code to retrieve the value of that option:

host = config.get('database', 'host')

To retrieve integers or boolean values, you can utilize the getint() and getboolean() methods.

port = config.getint('database', 'port')
ssl_enabled = config.getboolean('database', 'ssl_enabled')

Apart from the methods get(), getint(), and getboolean(), the configparser module also offers other methods for manipulating configuration files, such as the sections() method for retrieving the names of all sections, and the options() method for getting all options within a specified section.

The complete example code is as follows:

import configparser

config = configparser.ConfigParser()
config.read('config.ini')

host = config.get('database', 'host')
port = config.getint('database', 'port')
ssl_enabled = config.getboolean('database', 'ssl_enabled')

print(host, port, ssl_enabled)

Please make sure that the INI configuration file exists and is formatted correctly when reading it, as it may cause exceptions otherwise.

bannerAds