python - 如何使用配置解析器使配置文件属性唯一?
问题描述
如何创建一个只有一个唯一属性的配置文件?或者是否有任何循环来检查配置文件,我发现重复的名称属性值并且它给出了异常?
[NAME+TIMESTAMP]
Name=UNIQUE NAME
Property=something
Property1=something1
Property2=something2
[NAME+TIMESTAMP]
Name=UNIQUE NAME
Property=something
Property1=something1
Property2=something2
解决方案
由于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
推荐阅读
- python - 使用 sort() 方法时遇到问题
- php - 如何在shopify中使用oauth获取商家的店铺名称?
- python - 返回元组的 np.argmax
- google-cloud-platform - 通过 gcloud 清除 Google Cloud 上的 Airflow 任务
- c - 使用命名管道更好的方法
- javascript - Chart.js - 将蓝色实线变为红色虚线
- android - 获取设备内部存储(不是应用程序目录)和外部存储(SD卡),这是正确的方法吗?
- java - Java 扫描器要求输入两次
- java - 基于RequestBody参数获取Java Spring boot中的特定bean
- facebook-graph-api - 如何更新长寿命用户访问令牌(在其 60 天到期之前)