A custom ConfigParser class that preserves comments and option casing 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-configparser
From github:
python -m pip install commented-configparser@git+https://github.com/Preocts/commented-configparser@x.x.x
Note: Replace x.x.x
with the desired tag or branch.
from commentedconfigparser import CommentedConfigParser
# Load the config like normal
config = CommentedConfigParser()
config.read("myconfig.ini")
# Use the config like normal
...
# Update the config like normal
...
# Save the config back to the file
with open("myconfig.ini", "w") as savefile:
config.write(savefile)
We favor the line spacing choices of the ConfigParser
class so the input format may not be preserved completely. However, the comments will be preserved.
# Welcome to our config
[DEFAULT]
# This value has some meaning to someone
foo=bar
# Make sure to add this when you need it
trace=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 comment
multi-line=
value01
value02
value03
closing=0
# Trailing comment
# Welcome to our config
[DEFAULT]
# This value has some meaning to someone
foo = bar
# Make sure to add this when you need it
trace = 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 comment
multi-line =
value01
value02
value03
closing = 0
# Trailing comment