首页 > 解决方案 > 如何使用配置解析器使配置文件属性唯一?

问题描述

如何创建一个只有一个唯一属性的配置文件?或者是否有任何循环来检查配置文件,我发现重复的名称属性值并且它给出了异常?

[NAME+TIMESTAMP]
Name=UNIQUE NAME
Property=something
Property1=something1
Property2=something2

[NAME+TIMESTAMP]
Name=UNIQUE NAME
Property=something
Property1=something1
Property2=something2

标签: pythonparsingconfig

解决方案


由于configParser在大多数情况下都类似于 dict,我们可以在这里做的是使用key不同的代码块来确保有唯一的块。

这是一个简单的测试来展示它的实际效果:

import configparser
class 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-Object1
property1 = Something
property2 = Something2
property3 = Something3

[Test-Object2]
name = Test-Object2
property1 = Something Completely different
property2 = Something Completely different2
property3 = Something Completely different3

推荐阅读