9

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')
Giggi
  • 681
  • 2
  • 9
  • 17

1 Answers1

14

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
root
  • 76,608
  • 25
  • 108
  • 120
  • Ok I've read the documentation. But I really need to add a comment line runtime, that's useful for editing by hand the config file. – Giggi Oct 12 '12 at 06:46
  • See the examples, Is that what you mean? – root Oct 12 '12 at 06:50
  • Hi Root I have this as my properties and it keeps returning True `# Via .py directory data.extension=False # Via API # data.extension=True ` – Azy Sır Apr 30 '19 at 05:25
  • You have to use `getboolean('property')` to translate the string `True/False` into a boolean value. – Agoun Feb 25 '21 at 11:13