我可以使用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. configparser在寫出註釋時丟掉了註釋
- 4. 添加註釋值
- 5. 添加註釋列
- 6. 向Morris.js添加註釋/註釋
- 7. 使用DomDocument添加條件註釋
- 8. 使用perl添加註釋到pdf
- 9. json.net使用JsonConvert.SerializeObject添加註釋輸出
- 10. 使用地圖任務添加註釋。
- 11. 使用php和html添加註釋
- 12. 使用C + libxml ++添加XML註釋
- 13. 使用xpath添加SimpleDOM的註釋
- 14. 爲ggplot2添加一個註釋並添加一個註釋?
- 15. 在PDF中添加註釋
- 16. 添加註釋到PDF android
- 17. 在pdf上添加註釋
- 18. 手動添加註釋?
- 19. 添加註釋到交易
- 20. 停止ReSharper添加註釋
- 21. 添加註釋要在Excel
- 22. 添加方法groovy.util.logging.Slf4j註釋?
- 23. 在RCS中添加註釋
- 24. 將註釋添加到UIImageView
- 25. 向接口添加註釋
- 26. 添加註釋文件
- 27. 添加地圖註釋
- 28. 向PlotChart添加註釋
- 29. 將註釋添加到pdf
- 30. 在checkintool中添加註釋
請參閱接受的問題的答案[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