How to read configurations from an .ini file in Python

How to read configurations from an .ini file in Python

Reading a configuration file like .ini file is fairly simple in Python.

First we need to have an ini file as shown below :

# sample ini file for demonstration
[DEFAULT] # this is called a section, always kept in []
# everthing from here are key value pairs
IPAddress = 192:168:1:10  
Compression = yes
CompressionLevel = 9
ForwardX11 = yes

The above file is an .ini file which contains sections in square brackets as [SectionName]. Then a section contains few key value pairs as IPAddress = 192:168:1:10

To read such a file, we need to mention the section name as well as the key name inside the section whose value we want to retrieve.

Below mention code achieves the same functionality. Here you need to specify the section and key name to retrieve the corresponding value.

import configparser

class ConfigurationReader :
    # this is called constructor and it is called automatically on object creation
    # it is used to initialize the basic state of an object, like initializing few properties
    def __init__(self):     
        print('ConfigurationReader called.')     
        # example of relative path, it meant, in the same directory 
        # there is a folder called configs which contains configurations.ini   
        self.configurationFilePath = r'.\configs\configurations.ini'

    def FetchValue(self, section,key):
        # usage of configparser library to ini file
        configParser = configparser.RawConfigParser()   
        # Example of string interpolation
        print(f'Configuration file path : {self.configurationFilePath}') 
        # here ini file is being read
        # here the value of asked key from section is returned to calling function
        return configParser.get(section, key)

We have our ini file as well as the code to read it. Now we need an entry point to use the above mentioned code. Line 3 specified the way to import Line 6 specified how to create an object of ConfigurationReader and at Line 7, we are able to fetch the value of Key “IPAddress” from Section “DEFAULT”

# here libraries/classes are imported
import configparser # this one is python's own class
import ConfigurationReader # this is custom created, for possible re-use at later stage

# initialized an instance of ConfigurationReader class
configReader = ConfigurationReader.ConfigurationReader()
ipAddress = configReader.FetchValue('DEFAULT','IPAddress')

# here ip address from config file will be printed
print(f'Ip address from config file : {ipAddress}')

This repository will help you more :

Share and Enjoy !

0 0

2 thoughts on “How to read configurations from an .ini file in Python

Leave a Reply

Your email address will not be published. Required fields are marked *