A custom ConfigParser class that preserves comments and most formatting when writing loaded config out.
This library gives you a custom class of the standard library's
configparser.ConfigParger which will preserve the comments of a loaded config
file when writing that file back out.
From pypi:
python -m pip install commented-configparserFrom github:
python -m pip install commented-configparser@git+https://github.com/Preocts/commented-configparser@x.x.xNote: Replace x.x.x with the desired tag or branch.
fromcommentedconfigparserimportCommentedConfigParser# Load the config like normalconfig=CommentedConfigParser()
config.read("myconfig.ini")
# Use the config like normal
...
# Update the config like normal
...
# Save the config back to the filewithopen("myconfig.ini", "w") assavefile:
config.write(savefile)There is the attempt to retain the original format. Known formats that will not be preserved:
- Indents will not be preserved outside of multi-line values
- Spacing around assignments will be normalized.
# Welcome to our config[DEFAULT]# This value has some meaning to someonefoo=bar
# Make sure to add this when you need ittrace=false
logging=true
; This is a comment as well# so we need to track all of them; and many could be between things[NEW SECTION]# Another commentmultiLine=
value01
value02
value03
closing=0
# Trailing comment# Welcome to our config[DEFAULT]# This value has some meaning to someonefoo = bar
# Make sure to add this when you need ittrace = false
logging = true
; This is a comment as well# so we need to track all of them; and many could be between things[NEW SECTION]# Another commentmultiLine =
value01
value02
value03
closing = 0
# Trailing comment