2

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.

3 Answers3

3

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
  • 1
    First, welcome to Stack Overflow! As a community of people with varied backgrounds, this answer can help more than just the original poster. Would you be OK with adding a bit more information to your answer on how the Comments attributes work for each section? – Andrew Gray Oct 08 '18 at 21:31
0

This documentation will help you.

tl;dr :

example = StringIO('''
[test]
opt1 = 1
# this is a comment
; and so is this
opt2 = 2''')
safeconfigparser.readfp(example)
print safeconfigparser.items('test')

Hopefully this will help you, Yahli.

Mr Yahli
  • 321
  • 2
  • 13
0

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.

Jean-Pierre Schnyder
  • 1,572
  • 1
  • 15
  • 24