Open In App

How to Write a Configuration File in Python?

Last Updated : 27 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Configuring your Python applications using configuration files is a common practice that allows you to separate configuration details from your code, making it more modular and easier to manage. In this article, we’ll explore how to create a configuration file in Python, focusing on a simple and widely used format, the .ini file.

What is a Configuration File in Python?

A configuration file is a plain text file that contains parameters and settings for an application. These settings are often stored in a key-value pair format, making it easy to read and modify. The INI (Initialization) file format is a popular choice for configuration files due to its simplicity.

Python provides the config parser module in the standard library to work with configuration files. This module allows you to read and write configuration files in the INI format. Here, we will use this module to write a configuration file in Python.

Write a Configuration File in Python

Below are some of the examples by which we can understand about how we can write a configuration file in Python:

Installing configparser

Before using the configparser module, you don’t need to install anything since it’s part of the standard library. You can import it directly in your Python script or application.

Python3




import configparser


Creating a Configuration File

In this example, we create a ConfigParser object, add sections (General and Database), and populate them with key-value pairs. Finally, we write the configuration to a file named config.ini.

Python3




import configparser
 
 
def create_config():
    config = configparser.ConfigParser()
 
    # Add sections and key-value pairs
    config['General'] = {'debug': True, 'log_level': 'info'}
    config['Database'] = {'db_name': 'example_db',
                          'db_host': 'localhost', 'db_port': '5432'}
 
    # Write the configuration to a file
    with open('config.ini', 'w') as configfile:
        config.write(configfile)
 
 
if __name__ == "__main__":
    create_config()


config.ini

[General]
debug = True
log_level = info

[Database]
db_name = example_db
db_host = localhost
db_port = 5432

Reading a Configuration File in Python

In this example, the Python script uses the configparser module to read configuration values from a file named config.ini. The retrieved values, including boolean, string, and integer types, are stored in a dictionary (config_values) and printed to the console when the script is executed.

Python3




import configparser
 
 
def read_config():
    # Create a ConfigParser object
    config = configparser.ConfigParser()
 
    # Read the configuration file
    config.read('config.ini')
 
    # Access values from the configuration file
    debug_mode = config.getboolean('General', 'debug')
    log_level = config.get('General', 'log_level')
    db_name = config.get('Database', 'db_name')
    db_host = config.get('Database', 'db_host')
    db_port = config.get('Database', 'db_port')
 
    # Return a dictionary with the retrieved values
    config_values = {
        'debug_mode': debug_mode,
        'log_level': log_level,
        'db_name': db_name,
        'db_host': db_host,
        'db_port': db_port
    }
 
    return config_values
 
 
if __name__ == "__main__":
    # Call the function to read the configuration file
    config_data = read_config()
 
    # Print the retrieved values
    print("Debug Mode:", config_data['debug_mode'])
    print("Log Level:", config_data['log_level'])
    print("Database Name:", config_data['db_name'])
    print("Database Host:", config_data['db_host'])
    print("Database Port:", config_data['db_port'])


Output:

Debug Mode: True
Log Level: info
Database Name: example_db
Database Host: localhost
Database Port: 5432


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads