How to Parse INI Config Files in Python with configparser
Load and read settings from an INI file using Python's built-in configparser module, with type-safe value access.
Python code
42 linesimport configparser
from pathlib import Path
# Create a sample INI file for demonstration
sample_content = """
[Database]
host = localhost
port = 5432
user = admin
password = secret123
[Logging]
level = INFO
file = app.log
max_size = 10MB
"""
config_file = Path("sample_config.ini")
config_file.write_text(sample_content)
# Parse the INI file
config = configparser.ConfigParser()
config.read(config_file)
# Access values
db_host = config.get("Database", "host")
db_port = config.getint("Database", "port")
log_level = config["Logging"]["level"]
print(f"Database host: {db_host}")
print(f"Database port: {db_port}")
print(f"Log level: {log_level}")
# List all sections and keys
print("\nAll sections:")
for section in config.sections():
print(f" [{section}]")
for key, value in config.items(section):
print(f" {key} = {value}")
# Clean up the sample file
config_file.unlink()
Output
Database host: localhost
Database port: 5432
Log level: INFO
All sections:
[Database]
host = localhost
port = 5432
user = admin
password = secret123
[Logging]
level = INFO
file = app.log
max_size = 10MB
How it works
The configparser.ConfigParser object parses INI files into sections and key-value pairs. config.get() returns string values, while config.getint() auto-converts to integers — perfect for numeric settings. Use config.sections() and config.items(section) to iterate over groups dynamically. The Path object from pathlib handles file paths cleanly, and write_text() lets you create a sample file for testing. This approach keeps configuration separate from code, making it easy to adjust settings without touching the application logic.
Common mistakes
- Using `config.read()` with a non-existent file — it silently returns an empty config; check with `Path.is_file()` first.
- Forgetting to call `getint()`/`getboolean()` for numeric or boolean values, leaving them as strings that break comparisons.
- Assuming section names are case-insensitive — they are case-sensitive by default.
- Not cleaning up test files, which can leave junk on disk in CI environments.
Variations
- Use `config.getboolean('Logging', 'enabled')` to read true/false values as Python booleans.
- Use `config = configparser.ConfigParser(); config.read_dict({'Database': {'host': 'localhost'}})` for programmatic config without a file.
Real-world use cases
- Reading connection parameters (host, port, credentials) for a database when a service boots up.
- Loading logging thresholds, file paths, and rotation limits from a config file in CLI tools.
- Managing per-environment settings (dev/staging/prod) by swapping INI files at deploy time.
Sponsored
More from Files & data
- Append a Line to a Log File in Python easy
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a File Index by Relative Path Hash Map in Python easy
Keep learning
Related tutorials and quizzes for this topic.