If you want to get rid of the final = , you can subclass ConfigParser.ConfigParser as suggested by atomocopter and implement your own write method to replace the original:
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:
[Section] key = value ; this is the comment
Notes:
- If you use the name of a parameter whose name begins with
; , and the value is None , this will be considered a comment. - This will allow you to add comments and write them to files, but not read them. To do this, you will implement your own
_read method, which will take care of parsing comments and, possibly, add the comments method to get comments for each section.
source share