簡體   English   中英

使用Python將ini文件中的所有內容讀入字典

[英]Read all the contents in ini file into dictionary with Python

通常,我按如下方式編碼,以獲取變量中的特定項目,如下所示

try:
    config = ConfigParser.ConfigParser()
    config.read(self.iniPathName)
except ConfigParser.MissingSectionHeaderError, e:
    raise WrongIniFormatError(`e`)

try:
    self.makeDB = config.get("DB","makeDB")
except ConfigParser.NoOptionError:
    self.makeDB = 0

有沒有辦法讀取python字典中的所有內容?

例如

[A]
x=1
y=2
z=3
[B]
x=1
y=2
z=3

被寫入

val["A"]["x"] = 1
...
val["B"]["z"] = 3

我建議ConfigParser.ConfigParser (或SafeConfigParser ,&c)以安全地訪問“受保護”屬性(以單下划線開頭的名稱 - “private”將是以兩個下划線開頭的名稱,即使在子類中也不能訪問...) :

import ConfigParser

class MyParser(ConfigParser.ConfigParser):

    def as_dict(self):
        d = dict(self._sections)
        for k in d:
            d[k] = dict(self._defaults, **d[k])
            d[k].pop('__name__', None)
        return d

這模擬了配置解析器的通常邏輯,並保證在所有版本的Python中都有效,其中有一個ConfigParser.py模塊(最多2.7個,這是2.*系列中的最后一個 - 知道沒有未來Python 2.任何版本都可以保證兼容性;-)。

如果你需要支持未來的Python 3.*版本(最多3.1版本,可能是即將推出的3.2版本應該沒問題,只需將模塊重命名為全小寫的configparser而不是當然)它可能需要一些關注/調整幾年這條路,但我不指望有什么重大的。

我設法得到答案,但我希望應該有一個更好的答案。

dictionary = {}
for section in config.sections():
    dictionary[section] = {}
    for option in config.options(section):
        dictionary[section][option] = config.get(section, option)

ConfigParser的實例數據在內部存儲為嵌套的dict。 您可以復制它,而不是重新創建它。

>>> import ConfigParser
>>> p = ConfigParser.ConfigParser()
>>> p.read("sample_config.ini")
['sample_config.ini']
>>> p.__dict__
{'_defaults': {}, '_sections': {'A': {'y': '2', '__name__': 'A', 'z': '3', 'x': '1'}, 'B':         {'y': '2', '__name__': 'B', 'z': '3', 'x': '1'}}, '_dict': <type 'dict'>}
>>> d = p.__dict__['_sections'].copy()
>>> d
{'A': {'y': '2', '__name__': 'A', 'z': '3', 'x': '1'}, 'B': {'y': '2', '__name__': 'B', 'z': '3', 'x': '1'}}

編輯:

Alex Martelli的解決方案更清潔,更強大,更漂亮。 雖然這是公認的答案,但我建議改用他的方法。 有關詳細信息,請參閱他對此解決方案的評論

我知道這個問題是5年前提出的,但是今天我已經把這個詞匯理解得很好了:

parser = ConfigParser()
parser.read(filename)
confdict = {section: dict(parser.items(section)) for section in parser.sections()}

如何在py中解析ini文件?

import ConfigParser
config = ConfigParser.ConfigParser()
config.read('/var/tmp/test.ini')
print config.get('DEFAULT', 'network')

test.ini文件包含:

[DEFAULT]
network=shutup
others=talk

需要注意的另一件事是, ConfigParser將鍵值轉換為小寫,因此如果您將配置條目轉換為字典,請檢查您的要求。 因為這個我遇到了問題。 對我來說,我有駱駝式密鑰,因此,當我開始使用字典而不是文件時,必須更改一些代碼。 ConfigParser.get()方法在內部將密鑰轉換為小寫。

假設file:config.properties包含以下內容:

  • k = v
  • k2 = v2
  • k3 = v3

python代碼:

def read_config_file(file_path):
        with open(file=file_path, mode='r') as fs:
            return {k.strip(): v.strip() for i in [l for l in fs.readlines() if l.strip() != ''] for k, v in [i.split('=')]}


print('file as dic: ', read_config_file('config.properties'))

來自https://wiki.python.org/moin/ConfigParserExamples

def ConfigSectionMap(section):
dict1 = {}
options = Config.options(section)
for option in options:
    try:
        dict1[option] = Config.get(section, option)
        if dict1[option] == -1:
            DebugPrint("skip: %s" % option)
    except:
        print("exception on %s!" % option)
        dict1[option] = None
return dict1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM