https://github.com/preocts/commented-configparser
Custom ConfigParser class that preserves comments in file when writing
https://github.com/preocts/commented-configparser
configparser python3
Last synced: 11 months ago
JSON representation
Custom ConfigParser class that preserves comments in file when writing
- Host: GitHub
- URL: https://github.com/preocts/commented-configparser
- Owner: Preocts
- License: mit
- Created: 2022-11-01T19:53:11.000Z (over 3 years ago)
- Default Branch: main
- Last Pushed: 2025-03-04T02:42:27.000Z (12 months ago)
- Last Synced: 2025-04-03T19:16:18.263Z (11 months ago)
- Topics: configparser, python3
- Language: Python
- Homepage:
- Size: 125 KB
- Stars: 6
- Watchers: 2
- Forks: 4
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
Awesome Lists containing this project
README
[](https://www.python.org/downloads)
[](https://github.com/psf/black)
[](https://github.com/pre-commit/pre-commit)
[](https://results.pre-commit.ci/latest/github/Preocts/commented-configparser/main)
[](https://github.com/Preocts/commented-configparser/actions/workflows/python-tests.yml)
# commented-configparser
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.
---
## Install via pip
From pypi:
```bash
python -m pip install commented-configparser
```
From github:
```bash
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
```py
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
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.
### Before
```ini
# 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
```
### After
```ini
# 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
```