ConfigUpdater
ConfigUpdater is a Python library designed to update INI configuration files while preserving their original formatting, comments, and structure. It offers complementary functionality to Python's standard `ConfigParser`, which primarily focuses on reading and writing new files. The library aims for minimal, targeted changes, ensuring that the ordering of sections and key-value pairs, as well as their original casing, remain intact. The current version is 3.2, and it is actively maintained as part of the PyScaffold project.
Warnings
- gotcha Shallow copies of configuration blocks (sections, options, comments) are highly discouraged. Each block maintains a reference to its container, and using shallow copies for modifications can lead to unreliable and unexpected results.
- gotcha ConfigUpdater does *not* implement all features found in Python's standard `ConfigParser`. Specifically, it does not support value interpolation, propagation of parameters from the default section, value conversions, passing key/value pairs with default arguments, or a non-strict mode allowing duplicate sections and keys. Its focus is solely on minimal invasive updates.
- gotcha Direct assignment to an option's `.value` property (`updater['section']['key'].value = 'multi\nline'`) will fail if the value contains multiple lines. Multi-line values are explicitly disallowed for direct assignment.
Install
-
pip install configupdater
Imports
- ConfigUpdater
from configupdater import ConfigUpdater
Quickstart
import os
from configupdater import ConfigUpdater
# Create a dummy config file for demonstration
config_content = '''
[metadata]
author = Ada Lovelace
summary = The Analytical Engine
version = 1.0
[options]
verbose = yes
path = /tmp/data
'''
config_file_path = "example.ini"
with open(config_file_path, "w") as f:
f.write(config_content)
updater = ConfigUpdater()
updater.read(config_file_path)
# Change an existing value
updater["metadata"]["author"].value = "Grace Hopper"
# Add a new option
updater["metadata"]["license"] = "MIT"
# Add a new option with a comment before it
(updater["options"]["path"].add_before
.comment(" # Path to store temporary files")
.option("temp_dir", "/var/temp"))
# Remove an option
del updater["metadata"]["version"]
# Print the current state (optional)
# print(updater)
# Write the changes back to the original file
updater.update_file()
print(f"Updated configuration written to {config_file_path}")
with open(config_file_path, 'r') as f:
print(f.read())
# Clean up the dummy file
os.remove(config_file_path)