我可以使用python中的ConfigParser模块使用add_section和set方法创建ini文件(参见http://docs.python.org/library/configparser.html中的示例).但我没有看到任何关于添加评论的内容.那可能吗?我知道使用#和;但如何让ConfigParser对象为我添加?我在configparser的文档中没有看到任何相关内容.
解决方法:
如果你想摆脱trailing =,你可以按照atomocopter的建议继承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)
该脚本的输出是:
[Section]
key = value
; this is the comment
笔记:
>如果使用名称以?开头的选项名称;并且值设置为None,它将被视为注释.
>这将允许您添加注释并将其写入文件,但不会将其读回.要做到这一点,你将实现自己的_read方法,负责解析注释,并可能添加一个注释方法,以便获得每个部分的注释.
标签:python,configparser
来源: https://codeday.me/bug/20190621/1251931.html