Configuration files provide a structured way to manage application settings that are much more organized than just environment variables.
INI files, short for initialization files, are easy to read and easy to analyze, with their simple section-based format. Python built-in Config Parser module Makes working with these files straightforward and powerful.
This lesson will teach you how to read and analyze such readings .ini Create files using configparser Module
Conditions
To follow along with this tutorial, you should:
Python 3.7 or later installed on your system
Basic understanding of Python syntax and data structures (dictionaries, strings)
Familiarity with file operations in Python
A text editor or IDE for writing Python code
Basic knowledge of configuration files and why they are used in applications
No external package is required, as we will use Python’s built-in configparser Module
Table of Contents
Understanding the INI File Format
INI files organize sequences into sections, where each section contains key-value pairs. This structure is useful for applications with multiple components or environments. Let’s see what an INI file looks like before we analyze it.
Create a file named app.ini:
(database)
host = localhost
port = 5432
username = app_user
password = secure_password
pool_size = 10
ssl_enabled = true
(server)
host = 0.0.0.0
port = 8000
debug = false
(logging)
level = INFO
file = app.log
This file has three sections: Database, Server and Logging. Groups related settings from each section together, making the setting easier to understand and maintain.
Basic Config Parser usage
configparser The module provides ConfigParser class, which handles all the parsing tasks. Here’s how to read and access configuration values:
import configparser
config = configparser.ConfigParser()
config.read('app.ini')
db_host = config('database')('host')
db_port = config('database')('port')
print(f"Database: {db_host}:{db_port}")
print(f"Sections: {config.sections()}")
This code demonstrates the basic workflow:
a
ConfigParserobject,Read your INI file,
Then access the values using dictionary-like syntax.
The first bracket contains the name of the section, and the second contains the key.
make app.ini file and run the above code. You should see the following output:
Database: localhost:5432
Sections: ('database', 'server', 'logging')
Change and type the default values
Configuration values are stored as strings in INI files, but you often need them as integers, booleans, or floats. ConfigParser Provides simple methods for type conversions as shown here:
import configparser
config = configparser.ConfigParser()
config.read('app.ini')
db_port = config.getint('database', 'port')
ssl_enabled = config.getboolean('database', 'ssl_enabled')
max_retries = config.getint('database', 'max_retries', fallback=3)
timeout = config.getfloat('database', 'timeout', fallback=30.0)
print(f"Port: {db_port}, SSL: {ssl_enabled}")
In this code, getint()for , for , for , . getboolean()and getfloat() The methods convert the string value to the appropriate type. fallback The parameter provides a default value when the key does not exist, preventing errors.
When you run the above code, you will get:
Port: 5432, SSL: True
How to create a simple config manager
A practical approach is to wrap ConfigParser In a class that validates the configuration and provides easy access to the settings.
import configparser
from pathlib import Path
class ConfigManager:
def __init__(self, config_file='app.ini'):
self.config = configparser.ConfigParser()
if not Path(config_file).exists():
raise FileNotFoundError(f"Config file not found: {config_file}")
self.config.read(config_file)
def get_database_config(self):
db = self.config('database')
return {
'host': db.get('host'),
'port': db.getint('port'),
'username': db.get('username'),
'password': db.get('password'),
'pool_size': db.getint('pool_size', fallback=5)
}
This Manager class validates that the file exists and provides clean methods for accessing the configuration. It returns a dictionary with properly typed values.
And you can use it like this:
config = ConfigManager('app.ini')
db_config = config.get_database_config()
print(db_config)
These results:
{'host': 'localhost', 'port': 5432, 'username': 'app_user', 'password': 'secure_password', 'pool_size': 10}
How to work with multiple sections in INI files
You can organize different parts of your application into separate sections and access them independently:
import configparser
config = configparser.ConfigParser()
config.read('app.ini')
db_settings = dict(config('database'))
server_settings = dict(config('server'))
if config.has_section('cache'):
cache_enabled = config.getboolean('cache', 'enabled')
else:
cache_enabled = False
print(f"Database settings: {db_settings}")
print(f"Caching enabled: {cache_enabled}")
dict() Conversion gives you all key-value pairs from the same field. has_section() The method lets you conditionally handle optional sort fields.
Running the above code should give you the following output:
Database settings: {'host': 'localhost', 'port': '5432', 'username': 'app_user', 'password': 'secure_password', 'pool_size': '10', 'ssl_enabled': 'true'}
Caching enabled: False
How to write configuration files
ConfigParser INI files can also be created and edited, which is useful for saving user preferences or creating config templates:
import configparser
config = configparser.ConfigParser()
config('database') = {
'host': 'localhost',
'port': '5432',
'username': 'myapp'
}
config('server') = {
'host': '0.0.0.0',
'port': '8000',
'debug': 'false'
}
with open('generated.ini', 'w') as configfile:
config.write(configfile)
print("Configuration file created!")
This code creates a new INI file from scratch. The write() method saves the configuration in the appropriate INI format with segments and key-value pairs.
The result
When environment variables are not enough and you need grouped settings for different components, INI files are your answer.
The format is human readable, ConfigParser Handles type conversions automatically, and is built into Python’s standard library. Wrap it in a Configuration class for validation and clean access patterns.
Also remember:
Organize by component. Use sections for group-specific settings.
Use type conversion methods. Always use
getint()for , for , for , .getboolean()andgetfloat()Instead of manual conversion. They handle edge cases better.Provide sensible defaults. use
fallbackparameter for optional settings so your application works with minimal configuration.Verify soon. Check that startup contains the required sections and keys before attempting to use them.
Keep secrets separate. Do not put INI files with passwords in version control. use
.ini.exampleFiles with dummy values as templates.
In the next article, you’ll learn how to work with tuml files in Python. Until then, keep coding!