Search code examples
pythondictionaryconfigparser

Key, values under one header in .INI file


I have this code in Python which, given a dictionary, it writes the key:value fields in a config.ini file. The problem is that it keeps writing the header for each field.

import configparser

myDict = {'hello': 'world', 'hi': 'space'}

def createConfig(myDict):
    config = configparser.ConfigParser()

    # the string below is used to define the .ini header/title
    config["myHeader"] = {}
    with open('myIniFile.ini', 'w') as configfile:
        for key, value in myDict.items():
            config["myHeader"] = {key: value}
            config.write(configfile)

This is the output of .ini file:

[myDict]
hello = world

[myDict]
hi = space

How can I get rid of double title [myDict] and have the result like this

[myDict]
hello = world
hi = space

?

The code to create the .ini in Python has been taken from this question.


Solution

  • You get twice the header, because you write twice to the configfile. You should build a complete dict and write it in one single write:

    def createConfig(myDict):
        config = configparser.ConfigParser()
    
        # the string below is used to define the .ini header/title
        config["myHeader"] = {}
        for key, value in myDict.items():
            config["myHeader"][key] = value
        with open('myIniFile.ini', 'w') as configfile:
            config.write(configfile)