使用 Python3 读取和写入配置文件而不丢失文件中的注释

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

我想读取带有注释行的 INI 格式的配置文件。我不想在应用程序将配置写回文件时丢失这些行。

我该怎么做?

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

ConfigObj 是解决方案。