1

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.

num3ri
  • 822
  • 16
  • 20
lucians
  • 2,239
  • 5
  • 36
  • 64

3 Answers3

3

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)
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
1

This will do what you want:

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:
        config["myHeader"].update(myDict)
        config.write(configfile)
Marco Lombardi
  • 545
  • 4
  • 18
0

You could just to this:

def createConfig(myDict):
    config = configparser.ConfigParser()
    config["myIniFile"] = myDict
    with open('myIniFile.ini', 'w') as configfile:
        config.write(configfile)
Dominik K
  • 399
  • 3
  • 9