Nic*_*son 4 python configparser
我可以使用 python 中的 ConfigParser 模块使用 add_section 和 set 方法创建 ini 文件(参见http://docs.python.org/library/configparser.html 中的示例)。但我没有看到任何关于添加评论的内容。那可能吗?我知道使用 # 和 ; 但是如何让 ConfigParser 对象为我添加它?我在 configparser 的文档中没有看到任何关于此的内容。
如果你想摆脱尾随=,你可以ConfigParser.ConfigParser按照atomocopter的建议进行子类化,并实现你自己的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)
Run Code Online (Sandbox Code Playgroud)
这个脚本的输出是:
[Section]
key = value
; this is the comment
Run Code Online (Sandbox Code Playgroud)
笔记:
;且值设置为的选项名称None,它将被视为注释。_read方法来处理注释,并且可能添加一个comments方法来获取每个部分的注释。| 归档时间: |
|
| 查看次数: |
4062 次 |
| 最近记录: |