Convert ConfigParser.items('') to dictionary

后端 未结 9 1084
再見小時候
再見小時候 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: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()

提交回复
热议问题