Python Basics: Reading INI Settings with configparser
An INI file groups settings under section headings such as [app]. Python’s standard-library configparser module reads these settings and converts common value types.
Use Python 3.12 or newer in Bash on Linux. Each example runs independently; the file example uses an automatically cleaned temporary directory.
Read values and convert their types
Save as demo_configparser_1.py:
from configparser import ConfigParser
config = ConfigParser()
config.read_string("""
[app]
name = Notebook
workers = 3
enabled = no
""")
app = config["app"]
print("Name:", app["name"])
print("Workers:", app.getint("workers"))
print("Enabled:", app.getboolean("enabled"))Run it from the directory where you saved it:
python3 demo_configparser_1.pyOutput:
Name: Notebook
Workers: 3
Enabled: FalseValues start as strings. Use getint() and getboolean() for conversions: bool("no") would incorrectly give True because the string is nonempty. By default, option names ignore case, while section names are case-sensitive.
Open a required settings file
Save as demo_configparser_2.py:
from configparser import ConfigParser
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
path = Path(directory) / "settings.ini"
path.write_text("[display]\nlabel = 80% ready\n", encoding="utf-8")
config = ConfigParser(interpolation=None)
with path.open(encoding="utf-8") as source:
config.read_file(source)
print(config["display"]["label"])Run it from the directory where you saved it:
python3 demo_configparser_2.pyOutput:
80% readyOpening the file yourself makes a missing required file raise FileNotFoundError. In contrast, config.read() silently skips files it cannot open. Setting interpolation=None treats percent signs literally; the default parser gives % a special role in value substitution.
Separate missing settings from invalid ones
Save as demo_configparser_3.py:
from configparser import ConfigParser
config = ConfigParser()
config.read_string("[DEFAULT]\nretries = 3\n[worker]\nsize = many\n")
worker = config["worker"]
print("Retries:", worker.getint("retries", fallback=1))
print("Region:", worker.get("region", fallback="local"))
try:
worker.getint("size", fallback=10)
except ValueError:
print("Size must be an integer")Run it from the directory where you saved it:
python3 demo_configparser_3.pyOutput:
Retries: 3
Region: local
Size must be an integerDEFAULT supplies shared values before a fallback is considered. A fallback handles an absent option; it does not repair an invalid value. After conversion, check application rules too, such as requiring a positive size.
References
Acknowledgements
This post was created with assistance from AI.