Convert ConfigParser.items('') to dictionary

后端 未结 9 1083
再見小時候
再見小時候 2020-12-12 18:44

How can I convert the result of a ConfigParser.items(\'section\') to a dictionary to format a string like here:

import ConfigParser

config = ConfigParser.Co         


        
相关标签:
9条回答
  • 2020-12-12 19:42

    Here is another approach using Python 3.7 with configparser and ast.literal_eval:

    game.ini

    [assets]
    tileset = {0:(32, 446, 48, 48), 
               1:(96, 446, 16, 48)}
    

    game.py

    import configparser
    from ast import literal_eval
    
    config = configparser.ConfigParser()
    config.read('game.ini')
    
    # convert a string to dict
    tileset = literal_eval(config['assets']['tileset'])
    
    print('tileset:', tileset)
    print('type(tileset):', type(tileset))
    

    output

    tileset: {0: (32, 446, 48, 48), 1: (96, 446, 16, 48)}
    type(tileset): <class 'dict'>
    
    0 讨论(0)
  • 2020-12-12 19:43

    For an individual section, e.g. "general", you can do:

    dict(parser['general'])
    
    0 讨论(0)
  • 2020-12-12 19:43

    In Python +3.6 you could do this

    file.ini

    [SECTION1]
    one = 1
    two = 2
    
    [SECTION2]
    foo = Hello
    bar = World
    
    [SECTION3]
    param1 = parameter one
    param2 = parameter two
    

    file.py

    import configparser
    
    cfg = configparser.ConfigParser()
    cfg.read('file.ini')
    # Get one section in a dict
    numbers = {k:v for k, v in cfg['SECTION1'].items()}
    

    If you need all sections listed you should use cfg.sections()

    0 讨论(0)
提交回复
热议问题