Write comment in config files with python

Giggi picture Giggi · Oct 12, 2012 · Viewed 12.3k times · Source

I need to write some comment in a configuration file generated at runtime via ConfigParser library in Python.

I want to write a full descriptive comment like:

########################
# FOOBAR section 
# do something 
########################
[foobar]
bar = 1
foo = hallo

The code should look like:

Where I insert comment and configurations options in the same moment.

import ConfigParser

config = ConfigParser.ConfigParser()

config.insert_comment("##########################") # This function is purely hypothetical 
config.insert_comment("# FOOBAR section ")
....

config.add_section('foobar')
config.set('foobar', 'bar', '1')
config.set('foobar', 'foo', 'hallo')

Answer

root picture root · Oct 12, 2012

From the docs:

Lines beginning with '#' or ';' are ignored and may be used to provide comments.

Configuration files may include comments, prefixed by specific characters (# and ;). Comments may appear on their own in an otherwise empty line, or may be entered in lines holding values or section names. In the latter case, they need to be preceded by a whitespace character to be recognized as a comment. (For backwards compatibility, only ; starts an inline comment, while # does not.)

Examples:

conf.set('default_settings', '; comment here', '')

or

[default_settings]
    ; comment here = 
    test = 1

config = ConfigParser.ConfigParser()
config.read('config.ini')
print config.items('default_settings')

>>>
[('test','1')] # as you see comment is not parsed