Search code examples
pythonpython-2.7iniconfigparser

How to write ini-files without sections?


I need to create a file in the following format:

option1 = 99
option2 = 34
do_it = True
...

When I use ConfigParser, I have to put all my data into a section with an artificial name, and then it creates a file which starts with [SECTION].

import ConfigParser

ini_writer = ConfigParser.ConfigParser()
ini_writer.add_section('SECTION')
ini_writer.set('SECTION', 'option1', 99)
ini_writer.set('SECTION', 'option2', 34)
ini_writer.set('SECTION', 'do_it', True)
with open('my.ini', 'w') as f:
    ini_writer.write(f)

How can I change it so it outputs the file without the dummy section header? I would like to do it using Python 2.7, but a Python 3 solution would help too (the idea is that I could port it to Python 2.7).

This related question shows how to read such files using minor tweaks to the code.


Solution

  • [NB: the following is written for Python 3; you would need to make a couple of minor changes to make it run under Python 2.]

    Maybe something like this; here, I write to an io.StringIO object in memory, then take everything but the first line and write that out to the target file.

    import configparser
    import io
    
    
    buf = io.StringIO()
    
    ini_writer = configparser.ConfigParser()
    ini_writer.set('DEFAULT', 'option1', '99')
    ini_writer.set('DEFAULT', 'option2', '34')
    ini_writer.set('DEFAULT', 'do_it', 'True')
    ini_writer.write(buf)
    
    buf.seek(0)
    next(buf)
    with open('my.ini', 'w') as fd:
        fd.write(buf.read())
    

    By using the section name DEFAULT we avoid having to create a new section first.

    This results in:

    $ cat my.ini
    option1 = 99
    option2 = 34
    do_it = True