pythonconfigparser

Writing comments to files with ConfigParser


How can one write comments to a given file within sections?

If I have:

import ConfigParser
with open('./config.ini', 'w') as f:
    conf = ConfigParser.ConfigParser()
    conf.set('DEFAULT', 'test', 1)
    conf.write(f)

I will get the file:

[DEFAULT]
test = 1

But how can I get a file with comments inside [DEFAULT] section, like:

[DEFAULT]
; test comment
test = 1

I know I can write codes to files by doing:

import ConfigParser
with open('./config.ini', 'w') as f:
    conf = ConfigParser.ConfigParser()
    conf.set('DEFAULT', 'test', 1)
    conf.write(f)
    f.write('; test comment') # but this gets printed after the section key-value pairs

Is this a possibility with ConfigParser? And I don't want to try another module because I need to keep my program as "stock" as possible.


Solution

  • You can use the allow_no_value option if you have Version >= 2.7

    This snippet:

    import ConfigParser
    
    config = ConfigParser.ConfigParser(allow_no_value=True)
    config.add_section('default_settings')
    config.set('default_settings', '; comment here')
    config.set('default_settings', 'test', 1)
    with open('config.ini', 'w') as fp:
        config.write(fp)
    
    
    config = ConfigParser.ConfigParser(allow_no_value=True)
    config.read('config.ini')
    print config.items('default_settings')
    

    will create an ini file like this:

    [default_settings]
    ; comment here
    test = 1