Reading an INI File in Python

In Python, the configparser module is the standard library used for reading and writing INI files. This module provides a simple interface to access configuration data organized in sections and key-value pairs. Below, we will explore how to read an INI file in Python in detail, along with sample code.

1. Importing the ConfigParser Module

To read an INI file, you first need to import the configparser module. This module allows you to create a configuration parser object that can read the INI file.

Sample Code to Import ConfigParser:


import configparser

2. Creating a ConfigParser Object

After importing the module, you need to create an instance of the ConfigParser class. This object will be used to read the INI file and access its contents.

Sample Code to Create a ConfigParser Object:


config = configparser.ConfigParser()

3. Reading the INI File

Use the read method of the ConfigParser object to read the INI file. You can provide the filename as a string argument to this method.

Sample Code to Read the INI File:


config.read('config.ini')

4. Accessing Values from the INI File

Once the INI file is read, you can access the values using the section name and the key name. The syntax for accessing a value is config['SectionName']['KeyName'].

Sample Code to Access Values:


app_name = config['General']['app_name']
version = config['General']['version']

5. Complete Example

Below is a complete example that demonstrates how to read an INI file and access its values. Assume we have the following INI file named config.ini:


[General]
app_name = My Application
version = 1.0.0

[User ]
username = user123
password = secret

Complete Python Code to Read the INI File:


import configparser

# Create a ConfigParser object
config = configparser.ConfigParser()

# Read the INI file
config.read('config.ini')

# Accessing values
app_name = config['General']['app_name']
version = config['General']['version']
username = config['User ']['username']

# Print the values
print(f"Application Name: {app_name}")
print(f"Version: {version}")
print(f"Username: {username}")

6. Conclusion

Reading an INI file in Python is straightforward using the configparser module. By creating a ConfigParser object, reading the INI file, and accessing the values using section and key names, you can easily manage configuration settings in your applications. This approach allows for organized and maintainable configuration management.