Skip to content

A custom ConfigParser class that preserves comments and most formatting when writing loaded config out.

License

Notifications You must be signed in to change notification settings

Preocts/commented-configparser

Repository files navigation

Python 3.9 | 3.10 | 3.11 | 3.12 | 3.13 | 3.14 Code style: black pre-commit

pre-commit.ci status Python tests

commented-configparser


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.


Install via pip

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.


Example use

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)

Results

There is the attempt to retain the original format. Known formats that will not be preserved:

  1. Indents will not be preserved outside of multi-line values
  2. Spacing around assignments will be normalized.

Before

# 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
multiLine=
	value01
	value02
	value03
closing=0
# Trailing comment

After

# 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
multiLine =
	value01
	value02
	value03
closing = 0
# Trailing comment

About

A custom ConfigParser class that preserves comments and most formatting when writing loaded config out.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Contributors 3

  •  
  •  
  •  

Languages