configparser
— The configparser module provides the ConfigParser class for reading and writing configuration files in the INI file format. INI files are a simple text format with sections and key-value pairs, commonly used for application configuration. ConfigParser treats configuration files similar to dictionaries, with sections as top-level keys and options within each section. Values are stored as strings but can be automatically converted to integers, floats, or booleans using built-in getter methods.
Syntax
import configparser
# Create a parser
config = configparser.ConfigParser()
# Or with custom options
config = configparser.ConfigParser(
defaults={'debug': 'true'},
allow_no_value=True,
strict=False
)
ConfigParser Classes
configparser.ConfigParser
The main configuration parser class with interpolation support.
| Parameter | Type | Default | Description |
|---|---|---|---|
defaults | dict | None | Dictionary of default values for the DEFAULT section |
dict_type | type | dict | Dictionary class to use for sections and options |
allow_no_value | bool | False | Whether to accept options without values |
delimiters | tuple | ('=', ':') | Characters that separate keys from values |
comment_prefixes | tuple | ('#', ';') | Characters that start comments |
strict | bool | True | Whether to raise on duplicate sections/options |
interpolation | object | BasicInterpolation() | Value interpolation handler |
configparser.RawConfigParser
Legacy variant without interpolation by default, allows non-string values internally.
ConfigParser Methods
read()
Read and parse configuration files.
| Parameter | Type | Default | Description |
|---|---|---|---|
filenames | str/list | — | Single filename or iterable of filenames |
encoding | str | None | File encoding |
config.read('config.ini')
config.read(['site.cfg', 'user.cfg'], encoding='utf-8')
read_string()
Parse configuration from a string.
| Parameter | Type | Default | Description |
|---|---|---|---|
string | str | — | Configuration string to parse |
source | str | '<string>' | Name for error messages |
config.read_string("""
[DEFAULT]
debug = true
[database]
host = localhost
port = 5432
""")
read_dict()
Load configuration from a dictionary.
| Parameter | Type | Default | Description |
|---|---|---|---|
dictionary | dict | — | Dictionary with section names as keys |
source | str | '<dict>' | Name for error messages |
config.read_dict({
'DEFAULT': {'debug': 'true'},
'database': {'host': 'localhost', 'port': '5432'}
})
sections()
Return a list of section names (excluding DEFAULT).
config.sections()
# ['database', 'logging', 'server']
options(section)
Return list of options in a section.
config.options('database')
# ['host', 'port', 'user', 'password']
get(section, option, **kwargs)
Get a string value with optional fallback.
| Parameter | Type | Default | Description |
|---|---|---|---|
section | str | — | Section name |
option | str | — | Option name |
raw | bool | False | Disable interpolation |
vars | dict | None | Additional variables for interpolation |
fallback | any | None | Value if option not found |
config.get('database', 'host')
config.get('database', 'port', fallback=3306)
getint(section, option, **kwargs)
Get an integer value (convenience method).
port = config.getint('database', 'port')
# Returns: 5432 (as int)
getfloat(section, option, **kwargs)
Get a float value (convenience method).
rate = config.getfloat('rates', 'tax_rate')
# Returns: 0.0825 (as float)
getboolean(section, option, **kwargs)
Get a boolean value. Recognizes ‘yes’/‘no’, ‘true’/‘false’, ‘on’/‘off’, ‘1’/‘0’.
debug = config.getboolean('DEFAULT', 'debug')
# Returns: True (case-insensitive)
set(section, option, value)
Set an option value. Both option and value must be strings.
config.set('database', 'host', 'db.example.com')
config.set('database', 'port', '5432')
write(fileobject, space_around_delimiters=True)
Write configuration to a file.
| Parameter | Type | Default | Description |
|---|---|---|---|
fileobject | file | — | Open file object in text mode |
space_around_delimiters | bool | True | Add spaces around = and : |
with open('config.ini', 'w') as f:
config.write(f)
add_section(section)
Add a new section. Raises DuplicateSectionError if it exists.
config.add_section('new_section')
has_section(section)
Check if a section exists.
if config.has_section('database'):
# process database config
has_option(section, option)
Check if an option exists in a section.
config.has_option('database', 'host')
# Returns: True or False
remove_option(section, option)
Remove an option from a section.
config.remove_option('database', 'password')
remove_section(section)
Remove a section entirely.
config.remove_section('testing')
Examples
Creating and writing a config file
import configparser
config = configparser.ConfigParser()
config['DEFAULT'] = {
'debug': 'true',
'log_level': 'INFO'
}
config['database'] = {
'host': 'localhost',
'port': '5432',
'name': 'myapp'
}
config['server'] = {
'host': '0.0.0.0',
'port': '8080'
}
with open('config.ini', 'w') as f:
config.write(f)
# Output:
# [DEFAULT]
# debug = true
# log_level = INFO
#
# [database]
# host = localhost
# name = myapp
# port = 5432
#
# [server]
# host = 0.0.0.0
# port = 8080
Reading and accessing config values
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
# Access via mapping protocol
host = config['database']['host']
port = config['database']['port']
# Access via methods with type conversion
port_int = config.getint('database', 'port')
is_debug = config.getboolean('DEFAULT', 'debug')
# Iterate over sections and options
for section in config.sections():
print(f'[{section}]')
for key, value in config[section].items():
print(f' {key} = {value}')
Using interpolation
Interpolation lets values reference other values using %(key)s syntax:
config = configparser.ConfigParser()
config['paths'] = {
'home': '/home/user',
'data': '%(home)s/data',
'logs': '%(data)s/logs'
}
print(config.get('paths', 'data'))
# Output: /home/user/data
print(config.get('paths', 'logs'))
# Output: /home/user/data/logs
# Disable interpolation
config_no_interp = configparser.ConfigParser(interpolation=None)
config_no_interp.read_dict({'paths': {'data': '%(home)s/data'}})
print(config_no_interp.get('paths', 'data'))
# Output: %(home)s/data
Handling missing values with fallbacks
config = configparser.ConfigParser()
config.read_dict({
'database': {'host': 'localhost', 'port': '5432'}
})
# Fallback when option doesn't exist
timeout = config.get('database', 'timeout', fallback=30)
# Fallback with getboolean
debug = config.getboolean('database', 'debug', fallback=False)
# Using None as fallback
password = config.get('database', 'password', fallback=None)
if password is None:
print('No password configured')
Common Patterns
Loading config from multiple sources with priority
Later files override earlier ones for conflicting keys:
config = configparser.ConfigParser()
config.read(['defaults.cfg', 'site.cfg', 'local.cfg'])
# local.cfg has highest priority
Customizing boolean values
config = configparser.ConfigParser()
config.BOOLEAN_STATES = {'enabled': True, 'disabled': False, 'on': True, 'off': False}
config['app']['feature'] = 'enabled'
config.getboolean('app', 'feature') # Returns: True
Preserving case in option names
config = configparser.ConfigParser()
config.optionxform = str # Disable lowercase conversion
config.read_string("""
[Section]
OptionName = value
""")
print(list(config['Section'].keys()))
# Output: ['OptionName'] (not ['optionname'])
Working with options without values
config = configparser.ConfigParser(allow_no_value=True)
config.read_string("""
[settings]
debug
verbose = true
skip_validation
""")
print(config['settings']['debug'])
# Output: None
print(config['settings']['verbose'])
# Output: true
Errors
| Exception | Description |
|---|---|
NoSectionError | Requested section does not exist |
NoOptionError | Requested option does not exist |
DuplicateSectionError | Section already exists (in strict mode) |
DuplicateOptionError | Option already exists in section (strict mode) |
InterpolationError | Error during value interpolation |
ParsingError | Error parsing the configuration file |
try:
host = config.get('database', 'host')
except configparser.NoSectionError:
print('Database section not found')
except configparser.NoOptionError:
print('Host option not defined')
See Also
- argparse-module::argparse — command-line argument parsing
- json-module::json — JSON configuration files
- pathlib-module::pathlib — filesystem path handling
- tomllib — TOML file parsing (built-in since Python 3.11)