How do I write comments in ConfigObj?
I am using python 2.4.3 and ConfigObj 4.7
I don't see any methods in ConfigObj documentation.
How do I write comments in ConfigObj?
I am using python 2.4.3 and ConfigObj 4.7
I don't see any methods in ConfigObj documentation.
After a bit of testing, I found out you can also use the comments attribute for each section, here's a little example:
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()
This should generate the following file:
[section1]
# Comment before keyword1
key1 = value1 # Inline comment
# Comment before section2
[section2]
key2 = value2
The first answer is fully working. There's nevertheless a hidden HUGE problem: if you add an entry for key2 in the section1 inline_comments dictionary, you MUST add an entry for the new key in the section1 comments dictionary aswell, otherwise config.write() fails with the following exception:
Failing code:
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'
To fix the problem, simply uncomment the key2 entry in the comments dic.
In fact, every entry in a particular section must have a corresponding entry in this section comments or inline_comments dictionaries if those dics are used for this section.