Read all the contents in ini file into dictionary with Python

前端 未结 8 1880
天涯浪人
天涯浪人 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:14

    suppose file: config.properties contains the following:

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

    python code:

    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'))
    
    0 讨论(0)
  • 2020-12-04 23:23

    from 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
    
    0 讨论(0)
提交回复
热议问题