我可以使用ConfigParser模块在python中使用add_section和set方法创建ini文件(请参阅示例http://docs.python.org/library/configparser.html)。但我没有看到有关添加评论的任何内容。那可能吗?我知道使用#和;但如何让ConfigParser对象为我添加?在configparser的文档中我没有看到任何关于此的信息。使用configparser添加注释
3
A
回答
4
如果你想摆脱尾随=
的,你也可以继承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
方法,以便为每个部分获取评论。
1
做一个子类,或更容易:
import sys
import ConfigParser
ConfigParser.ConfigParser.add_comment = lambda self, section, option, value: self.set(section, '; '+option, value)
config = ConfigParser.ConfigParser()
config.add_section('Section')
config.set('Section', 'a', '2')
config.add_comment('Section', 'b', '9')
config.write(sys.stdout)
产生这样的输出:通过atomocopter
[Section]
a = 2
; b = 9
0
为了避免尾随“=”您可以使用sed命令与子模块,一旦你写的配置实例文件
**subprocess.call(['sed','-in','s/\\(^#.*\\)=/\\n\\1/',filepath])**
filepath是INI文件,你使用ConfigParser生成
相关问题
- 1. 添加注释
- 2. 添加注释列
- 3. 添加注释值
- 4. 使用地图任务添加注释。
- 5. 使用perl添加注释到pdf
- 6. 使用DomDocument添加条件注释
- 7. 添加注释文件
- 8. 添加方法groovy.util.logging.Slf4j注释?
- 9. 添加地图注释
- 10. 添加注释到交易
- 11. 将注释添加到UIImageView
- 12. 停止ReSharper添加注释
- 13. 添加注释到文件
- 14. 添加注释要在Excel
- 15. 在checkintool中添加注释
- 16. 用于在Javascript中添加注释/注释的示例代码
- 17. 使用注释
- 18. 使用注释注释Python print()输出
- 19. 如何在注释中使用注释?
- 20. 如何使用ActiveRecord为请求添加注释?
- 21. 使用ASM向外部类添加注释
- 22. 使用JET添加注释到数据库字段
- 23. 如何使用ASM添加自定义注释
- 24. 如何使用Roslyn将XML注释添加到MethodDeclarationSyntax节点?
- 25. 如何在C#中使用NPOI Excel添加单元格注释?
- 26. 快速使用AlertController在mapView上添加注释
- 27. 如何在Swagger2中使用Springfox添加自定义注释?
- 28. 使用VBA为单元格添加注释
- 29. 添加使用AOP @Schedule注释中的Java EE
- 30. web.config transform:添加XML注释以指示使用哪个配置
请参阅接受的问题的答案[Python ConfigParser关于将注释写入文件](http://stackoverflow.com/questions/6620637/python-configparser-question-about-writing-comments-to -fil es) – Chris 2011-12-16 12:24:01
哦。我没有看到答案。抱歉!这不是一个美丽的解决方案,但我想这是我必须这样做的方式。谢谢! – 2011-12-16 12:30:03
是的,这对于后面的`=`符号是一种遗憾,但似乎并没有太多可以做的事情! – Chris 2011-12-16 12:33:45