ConfigUpdater

3.2 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to read an INI file, modify an existing option, add new options (with and without comments), remove an option, and write the updated configuration back to the original file.

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)

view raw JSON →