python configparser 注释_python – 使用configparser添加注释

我可以使用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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值