gpt4 book ai didi

python - 使用 configparser 添加注释

转载 作者:太空狗 更新时间:2023-10-30 02:49:22 25 4
gpt4 key购买 nike

我可以使用 python 中的 ConfigParser 模块使用方法 add_section 和 set 创建 ini 文件(参见 http://docs.python.org/library/configparser.html 中的示例)。但我没有看到任何关于添加评论的内容。那可能吗?我知道使用 # 和 ;但是如何让 ConfigParser 对象为我添加它呢?我在 configparser 的文档中没有看到任何关于此的信息。

最佳答案

如果你想去掉尾随的 =,你可以按照 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 方法以获取每个部分的评论.

关于python - 使用 configparser 添加注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8533797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com