Python Reference ยท Files, Paths and Text I/O
The configparser module
Reference for Python's configparser module: read INI-style settings, get typed values with fallbacks, use DEFAULT and interpolation, and write config files.
The configparser module reads and writes configuration files in the INI format: named sections in square brackets, each holding key = value lines. It is a good fit for settings that people edit by hand.
A ConfigParser object behaves like a dictionary of sections, and each section behaves like a dictionary of strings. Values are always stored as strings, so the module provides getint(), getfloat() and getboolean() to convert them.
from configparser import ConfigParser config = ConfigParser() config.read_string("[server]\nport = 8080\n") print(config["server"]["port"])
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Main API
| Name | Description |
|---|---|
ConfigParser(defaults=None, interpolation=..., ...) |
Creates the parser. Many options exist; the defaults suit most files. |
read(filenames, encoding=None) |
Reads one or more files. Missing files are skipped silently; returns the list of files read. |
read_string(text), read_file(fileobj), read_dict(mapping) |
Read from a string, an open file or a nested dictionary. |
sections() |
List of section names (without DEFAULT). |
get(section, option, fallback=...) |
Returns a string. getint, getfloat and getboolean convert it. |
has_section(name), has_option(section, option) |
Existence tests. |
set(section, option, value), add_section(name), remove_option(), remove_section() |
Modify the configuration. |
write(fileobj) |
Writes the configuration in INI format. Comments from the original file are not kept. |
configparser.Error |
Base class of the module's exceptions, such as NoSectionError, NoOptionError and DuplicateSectionError. |
Usage notes
- Everything is a string. Assigning a number raises
TypeError; convert withstr()first. Use the typed getters when reading. getboolean()accepts1,yes,true,onas true and0,no,false,offas false (any case). Other text raisesValueError.- Option names are case-insensitive and stored in lower case, while section names are case-sensitive.
[DEFAULT]is special. Its keys appear in every section as fallbacks and are not listed bysections().- Interpolation. By default
%(name)srefers to another option in the same section (orDEFAULT). A literal percent sign in a value must be written%%, which is a common source ofInterpolationSyntaxError. Passinterpolation=Nonefor raw text, orExtendedInterpolation()to use${section:option}. - Fallbacks.
get(..., fallback=x)avoids exceptions for missing options. Dict-stylesection.get("key")returnsNoneinstead. - Comments and layout are lost on
write(). The module is meant for settings you load, not for editing a hand-formatted file in place. - Not for secrets. The file is plain text; use environment variables or a secrets store for passwords and tokens.
- TOML. For new projects,
tomllib(read-only, built in since Python 3.11) offers typed values and nested tables.
Related
json,argparse,os- Lessons: Files, Command-line programs, Dictionaries