ConfigObj
ConfigObj is a Python library for reading, writing, and validating configuration files. It supports a syntax similar to .ini files but adds features like nested sections, list handling, and comprehensive validation. It is currently at version 5.0.9 and is actively maintained with infrequent but important updates, often addressing security concerns or Python version compatibility.
Warnings
- breaking Python 2 support was entirely dropped in version 5.0.9, along with associated compatibility code. The minimum required Python version is now 3.7.
- breaking Version 5.0.9 addresses CVE-2023-26112, a Regular Expression Denial of Service (ReDoS) vulnerability. Older versions are susceptible to this vulnerability.
- gotcha Validation is not automatic. To enable validation, you must explicitly pass a `configspec` (a file path or a `ConfigObj` instance representing the specification) and then use a `Validate` object with `config.validate(validator)`.
- gotcha When working with lists, ConfigObj automatically converts comma-separated strings to lists upon writing. However, reading them back without a `configspec` will treat elements as strings. For robust type handling, especially with non-string list items, a `configspec` is essential.
Install
-
pip install configobj
Imports
- ConfigObj
from configobj import ConfigObj
- Validate
from configobj import Validate
Quickstart
from configobj import ConfigObj
import os
# 1. Create and write a config file
config = ConfigObj()
config.filename = "example.ini"
config['Section One'] = {
'key1': 'value1',
'key2': ['itemA', 'itemB', 'itemC']
}
config['Section Two'] = {}
config['Section Two']['nested_key'] = 'nested value'
config.write()
print(f"Config file 'example.ini' created.\n")
# 2. Read the config file
read_config = ConfigObj('example.ini')
print(f"Read config content:\n{read_config.dict()}\n")
print(f"Value from Section One, Key1: {read_config['Section One']['key1']}")
print(f"List from Section One, Key2: {read_config['Section One']['key2']}")
# 3. Clean up the created file
os.remove("example.ini")
print("example.ini removed.")