Read all the contents in ini file into dictionary with Python

前端 未结 8 1900
天涯浪人
天涯浪人 2020-12-04 22:28

Normally, I code as follows for getting a particular item in a variable as follows

try:
    config = ConfigParser.ConfigParser()
    config.read(self.iniPath         


        
8条回答
  •  半阙折子戏
    2020-12-04 23:03

    The instance data for ConfigParser is stored internally as a nested dict. Instead of recreating it, you could just copy it.

    >>> 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': }
    >>> d = p.__dict__['_sections'].copy()
    >>> d
    {'A': {'y': '2', '__name__': 'A', 'z': '3', 'x': '1'}, 'B': {'y': '2', '__name__': 'B', 'z': '3', 'x': '1'}}
    

    Edit:

    Alex Martelli's solution is cleaner, more robust, and prettier. While this was the accepted answer, I'd suggest using his approach instead. See his comment to this solution for more info.

提交回复
热议问题