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添加注释的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 北京环球影城机器人是真人表演吗
- 下一篇: 查表法实现反正切_关于python实现C