欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

python configparser 注释_使用configpar添加注释

发布时间:2023/12/1 python 52 豆豆
生活随笔 收集整理的这篇文章主要介绍了 python configparser 注释_使用configpar添加注释 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

如果您想去掉尾随的=,可以按照atomopter的建议将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)

此脚本的输出为:

^{pr2}$

注意事项:如果使用名称以;开头且值设置为None的选项名,则该选项将被视为注释。在

这将允许您添加注释并将其写入文件,但不会将其读回。为此,您将实现自己的_read方法,该方法负责解析注释,并可能添加一个comments方法来获得每个部分的注释。在

总结

以上是生活随笔为你收集整理的python configparser 注释_使用configpar添加注释的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。