A configuration file is a plain text file used to store application settings and parameters in a readable format.
- Settings are usually written as key–value pairs.
- The INI (Initialization) format is popular because it is simple and easy to read.
- Python provides the configparser module to work with INI files.
- The module allows reading from and writing to configuration files efficiently.
Write a Configuration File in Python
Store and manage application settings in Python using configuration files to improve flexibility, readability, and maintainability. Below are some examples that demonstrate how to write and use a configuration file in Python:
Installing configparser
The configparser module is included in Python’s standard library, so no additional installation is required. It can be imported directly into any Python script or application.
import configparser
Creating a Configuration File in Python
In this example, a ConfigParser object is created with two sections: General and Database. Each section contains key–value pairs, and the configuration is written to a file named config.ini.
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()
Output: Generated config.ini File
[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 configparser module is used to read values from the config.ini file. The retrieved values include boolean, string, and integer data types. These values are stored in a dictionary and printed to the console.
import configparser
def read_config():
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')
# Store retrieved values in a dictionary
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__":
config_data = read_config()
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