On this page
  1. configparser
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Reading with Safe Fallbacks & Writing Back to Disk
  7. 2. Preserving Key Case
  8. Gotchas & Boundaries
  9. Classes & Objects
  10. Constants & Attributes

configparser

Prev: concurrent | Up: stdlib_module | Next: contextlib
Rel: csv, tomllib, netrc, plistlib
Ref: docs.python.org — configparser
Tags: #public #python3 #stdlib


Import

import configparser

Overview

Reads and writes classic INI-style configuration files ([section] + key = value) with typed getters (getint, getfloat, getboolean), fallback defaults, and optional value interpolation. Prefer tomllib for new Python projects (pyproject.toml, typed arrays/nested tables); reach for configparser for existing .ini/.cfg files (such as .gitconfig or setup.cfg).

Quick Start

import configparser

cfg = configparser.ConfigParser()
cfg.read_string('''
[server]
host = 127.0.0.1
port = 8080
debug = yes
''')
assert cfg["server"]["host"] == "127.0.0.1"
assert cfg.getint("server", "port") == 8080
assert cfg.getboolean("server", "debug") is True

Implementation Walkthrough

1. Reading with Safe Fallbacks & Writing Back to Disk

import configparser
import io

cfg = configparser.ConfigParser(interpolation=None)
cfg["app"] = {"mode": "prod", "workers": "4"}
assert cfg.getint("app", "timeout", fallback=30) == 30

buf = io.StringIO()
cfg.write(buf)
assert "[app]" in buf.getvalue()

2. Preserving Key Case

By default, ConfigParser lowercases all option keys; set cfg.optionxform = str before reading if case matters:

import configparser

cfg = configparser.ConfigParser()
cfg.optionxform = str
cfg.read_string("[env]\nAPI_KEY = demo\n")
assert "API_KEY" in cfg["env"]

Gotchas & Boundaries

Classes & Objects

Constants & Attributes

Linked from

Related notes