configparser
The Python configparser
module provides tools for handling configuration files. It allows you to read, write, and manage user-editable configuration files in a standard format similar to Windows INI files.
Here’s a quick example:
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.read_string("""
... [DEFAULT]
... ServerAliveInterval = 45
... Compression = yes
... CompressionLevel = 9
... """)
>>> config["DEFAULT"]["Compression"]
'yes'
Key Features
- Reads and writes configuration files in INI format
- Supports interpolation, allowing you to use values from other sections
- Provides default values for sections
- Allows complex configurations with nested sections
Frequently Used Classes and Functions
Object | Type | Description |
---|---|---|
configparser.ConfigParser |
Class | Provides the main class for handling configuration files |
ConfigParser.read() |
Method | Reads a configuration file |
ConfigParser.get() |
Method | Retrieves the value for a given option |
ConfigParser.write() |
Method | Writes the configuration to a file |
Examples
Starting with the following configuration file:
example.ini
[DEFAULT]
ServerAliveInterval = 45
Compression = yes
CompressionLevel = 9
Reading existing values from a configuration file:
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.read("example.ini")
>>> config["DEFAULT"]["ServerAliveInterval"]
'45'
Writing a new value to a configuration file:
>>> config["NEW_SECTION"] = {"key": "value"}
>>> with open("example.ini", mode="w", encoding="utf-8") as configfile:
... config.write(configfile)
...
Common Use Cases
- Loading application settings from a file
- Allowing user-customizable configurations
- Managing complex configuration setups with default values and sections
Real-World Example
Imagine you have an application that needs to load user settings from a file. You can use configparser
to handle this task efficiently:
>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.read("settings.ini")
>>> config["UserSettings"] = {}
>>> config["UserSettings"]["theme"] = "dark"
>>> with open("settings.ini", mode="w", encoding="utf-8") as configfile:
... config.write(configfile)
...
In this example, configparser
allows you to load settings from an INI file, modify them, and save the changes back to the file, providing a straightforward way to handle user-configurable settings.
Related Resources
Tutorial
Raining Outside? Build a Weather CLI App With Python
In this tutorial, you'll write a nicely formatted Python CLI app that displays information about the current weather in any city you provide the name for.
For additional information on related topics, take a look at the following resources:
By Leodanis Pozo Ramos • Updated June 23, 2025