慕后森
由于configParser在大多数情况下都像 dict 一样,我们在这里可以做的是使用key不同的代码块来确保有唯一的块。这是一个简单的测试来展示它的实际效果:import configparserclass Container: configs=[] # keeps a list of all initialized objects. def __init__(self, **kwargs): for k,v in kwargs.items(): self.__setattr__(k,v) # Sets each named attribute to their given value. Container.configs.append(self)# Initializing some objects.Container( Name="Test-Object1", Property1="Something", Property2="Something2", Property3="Something3", )Container( Name="Test-Object2", Property1="Something", Property2="Something2", Property3="Something3", )Container( Name="Test-Object2", Property1="Something Completely different", Property2="Something Completely different2", Property3="Something Completely different3", )config = configparser.ConfigParser()for item in Container.configs: # Loops through all the created objects. config[item.Name] = item.__dict__ # Adds all variables set on the object, using "Name" as the key.with open("example.ini", "w") as ConfigFile: config.write(ConfigFile)在上面的示例中,我创建了三个包含要由 configparser 设置的变量的对象。但是,第三个对象Name与第二个对象共享变量。这意味着第三个将在写入 .ini 文件时“覆盖”第二个。例子.ini :[Test-Object1]name = Test-Object1property1 = Somethingproperty2 = Something2property3 = Something3[Test-Object2]name = Test-Object2property1 = Something Completely differentproperty2 = Something Completely different2property3 = Something Completely different3