.INI 文件中一个 header 下的键、值

Key, values under one header in .INI file

我在 Python 中有这段代码,给定一个字典,它将 key:value 字段写入 config.ini 文件。问题是它一直为每个字段写入 header。

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)

这是 .ini 文件的输出:

[myDict]
hello = world

[myDict]
hi = space

如何去掉双重标题 [myDict] 并得到这样的结果

[myDict]
hello = world
hi = space

?

在 Python 中创建 .ini 的代码取自 this question

您得到两倍的 header,因为您向配置文件写入了两次。你应该构建一个完整的 dict 并在一次写入中写入它:

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)

这会做你想做的事:

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)

你可以这样做:

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