Configparser

7.2.0 · active · verified Mon Apr 06

Configparser is a Python standard library module (also available as a backport for earlier Python versions) that provides tools for handling configuration files in INI format. It allows you to read, write, and manage user-editable configuration files, supporting features like sections, key-value pairs, default values, and value interpolation. The current backport version is 7.2.0 and it's actively maintained, periodically syncing with upstream CPython changes, making its features largely consistent with recent Python standard library versions.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a configuration, write it to an INI file, and then read values back using the `ConfigParser` class. It shows basic section and option access, as well as using fallback values for non-existent options.

import configparser
import os

# Create a configuration file programmatically
config = configparser.ConfigParser()
config['DEFAULT'] = {
    'ServerAliveInterval': '45',
    'Compression': 'yes',
    'ForwardX11': 'yes'
}
config['production.server'] = {
    'User': 'prod_user',
    'Port': '50022',
    'ForwardX11': 'no'
}

config_file_path = 'example.ini'
with open(config_file_path, 'w') as configfile:
    config.write(configfile)

print(f"Configuration written to {config_file_path}")

# Read the configuration file
read_config = configparser.ConfigParser()
read_config.read(config_file_path)

# Access values using dictionary-like syntax
print(f"Compression for DEFAULT: {read_config['DEFAULT']['Compression']}")
print(f"User for production.server: {read_config['production.server']['User']}")

# Get a value with fallback
port = read_config.get('development.server', 'Port', fallback='22')
print(f"Port for development.server (with fallback): {port}")

# Clean up the created file
os.remove(config_file_path)
print(f"Cleaned up {config_file_path}")

view raw JSON →