我如何在ConfigObj中编写注释?
我使用的是python 2.4.3和ConfigObj 4.7。
我在ConfigObj文档中没有看到任何方法。
我如何在ConfigObj中编写注释?
我使用的是python 2.4.3和ConfigObj 4.7。
我在ConfigObj文档中没有看到任何方法。
经过一些测试,我发现您还可以使用每个部分的注释属性,这里是一个小例子:
filename = 'test.ini'
config = ConfigObj(filename)
config['section1'] = {
'key1': 'value1'
}
config['section2'] = {
'key2': 'value2'
}
config['section1'].comments = {
'key1': ['Comment before keyword1',]
}
config['section1'].inline_comments = {
'key1': 'Inline comment'
}
config.comments['section2'] = ['Comment before section2']
config.write()
[section1]
# Comment before keyword1
key1 = value1 # Inline comment
# Comment before section2
[section2]
key2 = value2
第一个答案完全可行。然而,有个隐藏的巨大问题:如果你在section1的inline_comments字典中添加key2的条目,你必须同时在section1的comments字典中添加新key的条目,否则config.write()将失败并出现以下异常:
出错代码:
from configobj import ConfigObj
filename = 'test.ini'
config = ConfigObj(filename)
config['section1'] = {
'key1': 'value1',
'key2': 'value2',
}
config['section1'].comments = {
'key1': ['Comment before keyword1',],
# 'key2': [], missing key crashes ConfigObj.write()
}
config['section1'].inline_comments = {
'key1': 'Inline comment 1',
'key2': 'Inline comment 2',
}
config.write()
Traceback (most recent call last):
File "D:/Development/Python/GridView/inlcommwent.py", line 19, in <module>
config.write()
File "C:\Python37\lib\site-packages\configobj.py", line 2070, in write
out.extend(self.write(section=this_entry))
File "C:\Python37\lib\site-packages\configobj.py", line 2055, in write
for comment_line in section.comments[entry]:
KeyError: 'key2'
这个文档会帮助你。
简而言之:
example = StringIO('''
[test]
opt1 = 1
# this is a comment
; and so is this
opt2 = 2''')
safeconfigparser.readfp(example)
print safeconfigparser.items('test')