commented-configparser

raw JSON →
3.0.0 verified Sat May 09 auth: no python

A custom ConfigParser class that preserves comments and most formatting when writing loaded config out. Version 3.0.0 supports Python >=3.9. Release cadence is irregular.

pip install commented-configparser
error ModuleNotFoundError: No module named 'commented_configparser'
cause Package installed as 'commented-configparser' (dash) but imported as 'commented_configparser' (underscore).
fix
Install with pip install commented-configparser and import with from commented_configparser import CommentedConfigParser.
error AttributeError: 'CommentedConfigParser' object has no attribute 'write'
cause The library's write method is inherited from ConfigParser; if you override or use a different instance, it might be missing.
fix
Ensure you are using the CommentedConfigParser instance directly and not a different object.
breaking Version 2.x to 3.0.0 dropped Python 2 and older Python 3 versions; requires Python >=3.9. Also, the internal storage changed; any custom subclasses relying on internal data structures may break.
fix Upgrade to Python >=3.9 and adapt any custom subclasses to new internal representation.
gotcha Comments are preserved only if you use the same CommentedConfigParser to read and write. Using the stdlib ConfigParser will lose comments.
fix Always use CommentedConfigParser for both reading and writing if you want to preserve comments.
gotcha Multiline values may not preserve original formatting (e.g., indentation) after writing. The library attempts to preserve but edge cases exist.
fix Check the written file if exact formatting of multiline values is critical.

Read, modify, and write an INI file preserving comments and formatting.

from commented_configparser import CommentedConfigParser

config = CommentedConfigParser()
config.read('example.ini')
# Modify or add values
config.set('section', 'key', 'new_value')
# Write back preserving comments
with open('example.ini', 'w') as f:
    config.write(f)