我在Python中有这个代码,给定一个字典,它在config.ini文件中写入key:value字段。问题是它一直在为每个字段编写标题。
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。
你得到两倍的头,因为你写了两次配置文件。您应该构建一个完整的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)