Python configparser — Read INI Files, Sections, and Typed Values
A large share of program settings still live in INI files: a section header in brackets, then name and value lines under it. The configparser module reads that format with no package to install, and it adds the parts a plain text read does not have: a default section whose values fall back into every other section, typed getters that return integers, floats, and booleans, and interpolation that lets one value build on another. This guide takes those parts in turn, then the case rules, writing a file back out, and the errors a hand-edited file raises.
Written November 15, 2026 · Tested with Python 3.12.3 · 11 min read
- The main program: readstring and readfile
- Sections and the DEFAULT fallback
- Typed values: getint, getfloat, getboolean, and fallback
- Interpolation: one value built from another
Written November 15, 2026
Tested with Python 3.12.3
What this guide is
The configparser module reads INI files: text split into sections by headers such as [server], with one name = value pair per line under each header. A parsed file behaves like a dictionary of dictionaries. The outer keys are section names, each section holds its option names and values, and every value arrives as a string until a typed getter converts it. The module writes as well as reads, so a program can load a file, change values in memory, and write the result back in the same format.
The main program: read_string and read_file
Three read methods cover the three places the text can come from. read_string parses text the program already holds, read_file parses an open text file or any iterable of lines, and read takes one or more file names and opens them itself. The program below parses the same small file the first two ways:
import configparser, io
text = """[server]
host = example.com
port = 8080
[client]
retries = 3
"""
cfg = configparser.ConfigParser()
cfg.read_string(text)
print(cfg.sections())
print(cfg["server"]["host"], cfg["server"]["port"])
print(type(cfg["server"]["port"]).__name__)
cfg2 = configparser.ConfigParser()
cfg2.read_file(io.StringIO(text))
print(cfg2.sections())
print(cfg2["client"]["retries"])
The exact output:
['server', 'client']
example.com 8080
str
['server', 'client']
3
Two points in that output shape everything after it. sections() lists the named sections in file order, and the port prints as 8080 but its type is str: the parser stores text, and any number a program needs as a number goes through a typed getter, covered below. A real file follows the read_file shape with an opened file in place of the in-memory stream, or the shorter cfg.read("settings.ini") form, whose one trap is covered in the last section.
Sections and the DEFAULT fallback
One section name is special. Values under [DEFAULT] belong to no named section; instead they fall back into every section, so a shared setting is written once and read from any section. A section that sets the same name wins over the default, and the defaults also appear in each section's key list:
import configparser
text = """[DEFAULT]
timeout = 30
retries = 2
[server]
host = example.com
[client]
timeout = 5
"""
cfg = configparser.ConfigParser()
cfg.read_string(text)
print(cfg.sections())
print(cfg.defaults())
print(list(cfg["server"].keys()))
print(cfg["server"]["timeout"], cfg["client"]["timeout"])
print(cfg["client"]["retries"])
print("timeout" in cfg["server"])
The exact output:
['server', 'client']
{'timeout': '30', 'retries': '2'}
['host', 'timeout', 'retries']
30 5
2
True
sections() does not list DEFAULT, because it is not a section in the same sense; defaults() returns its pairs on their own. The fallback is per name, not per section: the client section overrides timeout and still inherits retries. Code that iterates a section's keys sees the defaults mixed in with the section's own names, which is the right behaviour for reading settings and a surprise for code that tries to list only what the file wrote under that header.
Typed values: getint, getfloat, getboolean, and fallback
Every value is stored as a string, and the typed getters convert on read. getint and getfloat parse the text as a number, and getboolean accepts a wider set than True and False: 1, yes, true, and on count as true, and 0, no, false, and off count as false, in any letter case. Each getter takes a fallback argument that is returned when the section or the option is missing, instead of an error:
import configparser
text = """[server]
port = 8080
ratio = 0.75
debug = yes
enabled = off
workers = many
"""
cfg = configparser.ConfigParser()
cfg.read_string(text)
s = cfg["server"]
print(s.getint("port"), type(s.getint("port")).__name__)
print(s.getfloat("ratio"))
print(s.getboolean("debug"), s.getboolean("enabled"))
print(cfg.getint("server", "missing", fallback=4))
print(cfg.getboolean("server", "verbose", fallback=False))
try:
s.getint("workers")
except ValueError as e:
print("ValueError:", e)
The exact output:
8080 int
0.75
True False
4
False
ValueError: invalid literal for int() with base 10: 'many'
The split between the two failure kinds is the part to keep. A missing name is a normal case, and fallback handles it. A present value that does not parse is a defect in the file, and the getter raises ValueError, the same error a direct int() call on that text raises. A program that supplies a fallback for every read still needs to decide what a bad value means, because the fallback does not cover it.
Interpolation: one value built from another
A value can refer to another value, and the parser expands the reference when the value is read. The default form is basic interpolation, where %(name)s inserts the value of name from the same section, or from DEFAULT. Extended interpolation, selected at construction, uses ${section:name} and can reach across sections. Passing interpolation=None turns the mechanism off, and the reference text is then returned as written:
import configparser
text = """[paths]
base = /srv/app
data = %(base)s/data
log = ${paths:base}/logs
"""
basic = configparser.ConfigParser()
basic.read_string(text)
print(basic["paths"]["data"])
ext = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
ext.read_string(text)
print(ext["paths"]["log"])
raw = configparser.ConfigParser(interpolation=None)
raw.read_string(text)
print(raw["paths"]["data"])
print(raw["paths"]["log"])
The exact output:
/srv/app/data
/srv/app/logs
%(base)s/data
${paths:base}/logs
Each parser in that program read the same text, and each form left the other form's reference untouched: the basic parser expanded only its own syntax, and the extended parser only its own. A literal percent sign in a value under basic interpolation is written as %%, which the parser collapses to one. Configuration that stores text full of percent signs or dollar braces, such as format strings for another tool, is the usual case for turning interpolation off: the values then mean exactly what the file says.
Case, delimiters, and multiline values
Option names and section names follow different case rules. Option names are case-insensitive: the parser folds them to lowercase as it reads, so Host and HOST are the same option, and a section's key list shows the folded form. Section names are case-sensitive: [Server] and [server] are two different sections. The value delimiter can be = or :, a line with a delimiter and nothing after it stores an empty string, and a value continues onto the next line when that line is indented deeper than the option line:
import configparser
text = """[Server]
Host = example.com
Port: 8080
empty =
note = first line
second line
"""
cfg = configparser.ConfigParser()
cfg.read_string(text)
print(cfg.sections())
print(list(cfg["Server"].keys()))
print(cfg["Server"]["host"], cfg["Server"]["HOST"])
print(repr(cfg["Server"]["empty"]))
print(repr(cfg["Server"]["note"]))
try:
cfg["server"]
except KeyError as e:
print("KeyError:", e)
cfg2 = configparser.ConfigParser(allow_no_value=True)
cfg2.read_string("[flags]\nverbose\ndebug = yes\n")
print(cfg2["flags"]["verbose"])
print(list(cfg2["flags"].keys()))
The exact output:
['Server']
['host', 'port', 'empty', 'note']
example.com example.com
''
'first line\nsecond line'
KeyError: 'server'
None
['verbose', 'debug']
The last part of the program covers the one line form the default parser rejects: a name with no delimiter at all. With allow_no_value=True such a line is accepted and its value is None, which suits flag-style files where the presence of the name is the setting. Without that option the same line is a parsing error. The multiline value joins its lines with a newline, as the note value shows; the indentation is part of the syntax, not part of the value.
Writing a configuration back out
A parser holds its data as a dictionary of dictionaries, so building one in code uses the same shape as reading one: assign a dictionary to a section name, then set options inside it. write sends the result to an open text file, with sections in insertion order, each option as name = value, and a blank line after each section. Values must be strings, since strings are all the format holds:
import configparser, io
cfg = configparser.ConfigParser()
cfg["server"] = {"host": "example.com", "port": "8080"}
cfg["client"] = {}
cfg["client"]["retries"] = "3"
out = io.StringIO()
cfg.write(out)
print(repr(out.getvalue()))
back = configparser.ConfigParser()
back.read_string(out.getvalue())
print(back.sections())
print(back["server"]["port"], back["client"]["retries"])
The exact output:
'[server]\nhost = example.com\nport = 8080\n\n[client]\nretries = 3\n\n'
['server', 'client']
8080 3
The round trip through write and a fresh parse returns the same sections and values, which is the test a save routine needs. What the round trip does not keep is the original file's comments and blank-line layout: the parser does not store comments, so a load, change, and save cycle rewrites the file in the standard layout. A file whose comments carry meaning for its readers is a poor fit for that cycle.
The traps: duplicates, missing headers, and the silent read
MissingSectionHeaderError. A repeated section header raises DuplicateSectionError, and a repeated option inside one section raises DuplicateOptionError; both can be turned off with strict=False, at the price of later values silently replacing earlier ones. A reference to a name that interpolation cannot find raises InterpolationMissingOptionError when the value is read, not when the file is parsed. Reading a missing section or option through dictionary access raises KeyError:import configparser
cases = [
"host = example.com\n",
"[a]\nx = 1\n[a]\ny = 2\n",
"[a]\nx = 1\nx = 2\n",
"[a]\npath = %(missing)s/x\n",
]
for text in cases:
cfg = configparser.ConfigParser()
try:
cfg.read_string(text)
print(cfg["a"]["path"])
except configparser.Error as e:
print(type(e).__name__)
cfg = configparser.ConfigParser()
cfg.read_string("[a]\nx = 1\n")
for fn in (lambda: cfg["missing"], lambda: cfg["a"]["y"]):
try:
fn()
except Exception as e:
print(type(e).__name__ + ":", e)
print(configparser.ConfigParser().read("no-such-file-xyz.ini"))
The exact output:
MissingSectionHeaderError
DuplicateSectionError
DuplicateOptionError
InterpolationMissingOptionError
KeyError: 'missing'
KeyError: 'y'
[]
The last line is the quietest trap in the module. read returns the list of files it parsed, and a file that does not exist is skipped without an error, so a mistyped path produces an empty configuration and a program that runs on defaults. Checking the returned list, or opening the file and using read_file, turns that silent case into an explicit one. All of the parse errors subclass configparser.Error, so one except clause around a parse catches the whole family while a program works out which failures it wants to name for the person editing the file.
Which choice for which job
| Job | Choice | Why |
|---|---|---|
| Parse text the program holds | read_string |
Takes a str directly |
| Parse an open file | read_file |
A missing file fails at the open, not silently |
| Parse files by name | read, checking its return list |
Skips missing files without an error |
| A setting shared by all sections | A [DEFAULT] value |
Falls back into every section |
| A number or a boolean setting | getint, getfloat, getboolean |
Converts the stored string on read |
| A possibly missing setting | The fallback argument |
Returns the fallback instead of raising |
| A value built from another value | Interpolation | Expanded at read time from the named value |
Stored text with % or ${} in it |
interpolation=None |
Values returned exactly as written |
| A flag with no value | allow_no_value=True |
The name alone is accepted, value None |
Checklist
- Remember that every value arrives as a string; convert with the typed getters where a number or a boolean is needed.
- Put shared settings in
[DEFAULT], and expect them to appear in every section's key list. - Use
fallbackfor settings that may be absent, and expect a present value that does not parse to raiseValueErroranyway. - Treat option names as lowercase and section names as case-sensitive, because the parser does.
- Turn interpolation off for files whose values hold percent signs or braces meant for another tool.
- Check the list
readreturns, so a missing file is a reported problem instead of an empty configuration. - Expect a load and save cycle to drop comments, because the parser does not store them.
Related guides on this site
- Python tomllib — Parse TOML with Loads and Load — the other standard-library configuration parser, read-only and typed where this one is string-based.
- Python JSON — dumps and loads — the third configuration form, with nested data the INI format does not have.
- Python files — open, read, and write — the open modes behind
read_fileand the file objectwriteneeds.
Sources
- Python Standard Library,
configparser—read,read_string,read_file, the typed getters andfallback, interpolation, the case rules,write, and the exception family.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.