Properties file in python (similar to Java Properties)

后端 未结 25 2820
故里飘歌
故里飘歌 2020-11-29 17:41

Given the following format (.properties or .ini):

propertyName1=propertyValue1
propertyName2=propertyValue2
...
propertyNam         


        
25条回答
  •  天命终不由人
    2020-11-29 18:25

    If you need to read all values from a section in properties file in a simple manner:

    Your config.properties file layout :

    [SECTION_NAME]  
    key1 = value1  
    key2 = value2  
    

    You code:

       import configparser
    
       config = configparser.RawConfigParser()
       config.read('path_to_config.properties file')
    
       details_dict = dict(config.items('SECTION_NAME'))
    

    This will give you a dictionary where keys are same as in config file and their corresponding values.

    details_dict is :

    {'key1':'value1', 'key2':'value2'}
    

    Now to get key1's value : details_dict['key1']

    Putting it all in a method which reads that section from config file only once(the first time the method is called during a program run).

    def get_config_dict():
        if not hasattr(get_config_dict, 'config_dict'):
            get_config_dict.config_dict = dict(config.items('SECTION_NAME'))
        return get_config_dict.config_dict
    

    Now call the above function and get the required key's value :

    config_details = get_config_dict()
    key_1_value = config_details['key1'] 
    

    -------------------------------------------------------------

    Extending the approach mentioned above, reading section by section automatically and then accessing by section name followed by key name.

    def get_config_section():
        if not hasattr(get_config_section, 'section_dict'):
            get_config_section.section_dict = dict()
    
            for section in config.sections():
                get_config_section.section_dict[section] = 
                                 dict(config.items(section))
    
        return get_config_section.section_dict
    

    To access:

    config_dict = get_config_section()
    
    port = config_dict['DB']['port'] 
    

    (here 'DB' is a section name in config file and 'port' is a key under section 'DB'.)

提交回复
热议问题