亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用配置解析器使配置文件屬性唯一?

如何使用配置解析器使配置文件屬性唯一?

12345678_0001 2022-12-06 16:37:12
如何創建一個只有一個唯一屬性的配置文件?或者是否有任何循環用于檢查配置文件,我在其中找到重復的名稱屬性值并且它給出了異常?[NAME+TIMESTAMP]Name=UNIQUE NAMEProperty=somethingProperty1=something1Property2=something2[NAME+TIMESTAMP]Name=UNIQUE NAMEProperty=somethingProperty1=something1Property2=something2
查看完整描述

1 回答

?
肥皂起泡泡

TA貢獻1829條經驗 獲得超6個贊

由于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


查看完整回答
反對 回復 2022-12-06
  • 1 回答
  • 0 關注
  • 142 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號