如何在ConfigObj中编写注释?
我使用的是Python2.4.3和ConfigObj 4.7
我在ConfigObj文档中看不到任何方法。
发布于 2018-10-09 05:07:59
经过一些测试,我发现您还可以对每个部分使用comments属性,下面是一个小示例:
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发布于 2017-05-09 18:56:14
This 文档将对您有所帮助。
tl;dr:
example = StringIO('''
[test]
opt1 = 1
# this is a comment
; and so is this
opt2 = 2''')
safeconfigparser.readfp(example)
print safeconfigparser.items('test')希望这能帮到你,雅莉。
发布于 2018-11-25 02:11:05
第一个答案是完全有效的。然而,还有一个隐藏的大问题:如果您在section1 inline_comments字典中为key2添加了一个条目,那么您也必须在section1注释字典中为新的键添加一个条目,否则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'要解决这个问题,只需在注释dic中取消对key2条目的注释。
事实上,如果注释或inline_comments字典用于此部分,则特定部分中的每个条目都必须在此部分中具有相应的条目。
https://stackoverflow.com/questions/43867144
复制相似问题