python – 使用configparser添加注释
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – 使用configparser添加注释,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1594字,纯文字阅读大概需要3分钟。
内容图文
![python – 使用configparser添加注释](/upload/InfoBanner/zyjiaocheng/799/bdf6cb2e71da4dcfbe29bb9553fe0eba.jpg)
我可以使用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添加注释全部内容,希望文章能够帮你解决python – 使用configparser添加注释所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。