Search code examples
pythonpython-3.xconfiguration-files

Read and write a config file with Python3 without losing the comments in the file


I want to read a configuration file in INI format that has comment lines. I don't want to lose those lines when the application writes the configuration back to the file.

How can I do this?

Python 3.6.5rc1 (default, Mar 14 2018, 06:54:23) 
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import configparser
>>> cfg = configparser.ConfigParser()
>>> cfg.read_string('''[DEFAULT]
... # comment
... parameter = 7''')
>>> f = open('my.conf', 'w')
>>> cfg.write(f)
>>> f.close()
>>> 
$ cat my.conf
[DEFAULT]
parameter = 7

Solution

  • The ConfigObj is the solution.