如果您想去掉尾随的=,可以按照atomopter的建议将ConfigParser.ConfigParser子类化,并实现自己的write方法来替换原来的方法: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)
此脚本的输出为:
^{pr2}$
注意事项:如果使用名称以;开头且值设置为None的选项名,则该选项将被视为注释。在
这将允许您添加注释并将其写入文件,但不会将其读回。为此,您将实现自己的_read方法,该方法负责解析注释,并可能添加一个comments方法来获得每个部分的注释。在