我可以使用python中的ConfigParser模块使用add_section和set方法创建ini文件(参见http://docs.python.org/library/configparser.html中的示例)。但我没有看到任何关于添加评论的内容。那可能吗?我知道使用#和;但如何让ConfigParser对象为我添加?我在configparser的文档中没有看到任何相关内容。
答案 0 :(得分:4)
如果你想摆脱尾随的=
,你可以按照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
方法,该方法负责解析注释,并可能添加comments
方法,以便为每个部分获取注释。答案 1 :(得分:1)
创建一个子类,或更简单:
import sys
import ConfigParser
ConfigParser.ConfigParser.add_comment = lambda self, section, option, value: self.set(section, '; '+option, value)
config = ConfigParser.ConfigParser()
config.add_section('Section')
config.set('Section', 'a', '2')
config.add_comment('Section', 'b', '9')
config.write(sys.stdout)
生成此输出:
[Section]
a = 2
; b = 9
答案 2 :(得分:0)
为了避免尾随“=”,一旦将配置实例写入文件,就可以将sed命令与子进程模块一起使用
<强> **subprocess.call(['sed','-in','s/\\(^#.*\\)=/\\n\\1/',filepath])**
强>
filepath是您使用ConfigParser生成的INI文件