If you want to get rid of the trailing =, you can subclass ConfigParser.ConfigParser as suggested by atomocopter and implement your own write method to replace the original one:
import sys
import ConfigParser
class ConfigParserWithComments(ConfigParser.ConfigParser):
def add_comment(self, section, comment):
self.set(section, '; %s' % (comment,), None)
def write(self, fp):
"""Write an .ini-format representation of the configuration state."""
if self._defaults:
fp.write("[%s]\n" % ConfigParser.DEFAULTSECT)
for (key, value) in self._defaults.items():
self._write_item(fp, key, value)
fp.write("\n")
for section in self._sections:
fp.write("[%s]\n" % section)
for (key, value) in self._sections[section].items():
self._write_item(fp, key, value)
fp.write("\n")
def _write_item(self, fp, key, value):
if key.startswith(';') and value is None:
fp.write("%s\n" % (key,))
else:
fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
config = ConfigParserWithComments()
config.add_section('Section')
config.set('Section', 'key', 'value')
config.add_comment('Section', 'this is the comment')
config.write(sys.stdout)
The output of this script is:
[Section]
key = value
; this is the comment
Notes:
If you use an option name whose name starts with ; and value is set to None, it will be considered a comment.
This will let you add comments and write them to files, but not read them back. To do that, you'll have implement your own _read method that takes care of parsing comments and maybe add a comments method to make it possible to get the comments for each section.