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.

Easy Python 3.9+ Aug 9, 2026 Files & data 12 views 0 copies

Python code

42 lines
Python 3.9+
import 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

stdout
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

  1. Use `config.getboolean('Logging', 'enabled')` to read true/false values as Python booleans.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Files & data

Related tutorials and quizzes for this topic.