pythonpython-3.xconfigurationiniconfigparser

Is it possible to keep the format of INI file after change it with ConfigParser?


Is it possible that ConfigParser keeps the format of INI config file? I have config files which have comments and specific section/option names and if a read and change the content of file the ConfigParser re-format it (I can solve the section/option names).

I am familiar with the way of working of ConfigParser (Read key/value pairs to a dict and dumping it to the file after change). But I am interested if there is solution to keep the original format and comments in the INI file.

Example:

test.ini

# Comment line
; Other Comment line
[My-Section]
Test-option = Test-Variable

test.py

import configparser as cp

parser: cp.ConfigParser = cp.ConfigParser()
parser.read("test.ini")

parser.set("My-Section", "New-Test_option", "TEST")

with open("test.ini", "w") as configfile:
    parser.write(configfile)

test.ini after run script

[My-Section]
test-option = Test-Variable
new-test_option = TEST

As you can see above the comment lines (both types of comments) have been removed. Furthermore, the option names have been re-formatted.

If I add the following line to source code then I can keep the format of the options but the comments are still removed:

parser.optionxform = lambda option: option

So the test.ini file after run the script with above line:

[My-Section]
Test-option = Test-Variable
New-Test_option = TEST

So my question(s):

Note:


Solution

  • I have found the configobj Python module which does what I want.

    As their documentation says:

    All comments in the file are preserved

    The order of keys/sections is preserved

    I have changed the build-in configparser to configobj and it works as charm.