Properties file in python (similar to Java Properties)

后端 未结 25 2652
故里飘歌
故里飘歌 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'.)

    0 讨论(0)
  • 2020-11-29 18:26

    I know that this is a very old question, but I need it just now and I decided to implement my own solution, a pure python solution, that covers most uses cases (not all):

    def load_properties(filepath, sep='=', comment_char='#'):
        """
        Read the file passed as parameter as a properties file.
        """
        props = {}
        with open(filepath, "rt") as f:
            for line in f:
                l = line.strip()
                if l and not l.startswith(comment_char):
                    key_value = l.split(sep)
                    key = key_value[0].strip()
                    value = sep.join(key_value[1:]).strip().strip('"') 
                    props[key] = value 
        return props
    

    You can change the sep to ':' to parse files with format:

    key : value
    

    The code parses correctly lines like:

    url = "http://my-host.com"
    name = Paul = Pablo
    # This comment line will be ignored
    

    You'll get a dict with:

    {"url": "http://my-host.com", "name": "Paul = Pablo" }
    
    0 讨论(0)
  • 2020-11-29 18:26

    I followed configparser approach and it worked quite well for me. Created one PropertyReader file and used config parser there to ready property to corresponding to each section.

    **Used Python 2.7

    Content of PropertyReader.py file:

    #!/usr/bin/python
    import ConfigParser
    
    class PropertyReader:
    
    def readProperty(self, strSection, strKey):
        config = ConfigParser.RawConfigParser()
        config.read('ConfigFile.properties')
        strValue = config.get(strSection,strKey);
        print "Value captured for "+strKey+" :"+strValue
        return strValue
    

    Content of read schema file:

    from PropertyReader import *
    
    class ReadSchema:
    
    print PropertyReader().readProperty('source1_section','source_name1')
    print PropertyReader().readProperty('source2_section','sn2_sc1_tb')
    

    Content of .properties file:

    [source1_section]
    source_name1:module1
    sn1_schema:schema1,schema2,schema3
    sn1_sc1_tb:employee,department,location
    sn1_sc2_tb:student,college,country
    
    [source2_section]
    source_name1:module2
    sn2_schema:schema4,schema5,schema6
    sn2_sc1_tb:employee,department,location
    sn2_sc2_tb:student,college,country
    
    0 讨论(0)
  • 2020-11-29 18:27

    For .ini files there is the ConfigParser module that provides a format compatible with .ini files.

    Anyway there's nothing available for parsing complete .properties files, when I have to do that I simply use jython (I'm talking about scripting).

    0 讨论(0)
  • 2020-11-29 18:27

    this works for me.

    from pyjavaproperties import Properties
    p = Properties()
    p.load(open('test.properties'))
    p.list()
    print p
    print p.items()
    print p['name3']
    
    0 讨论(0)
  • 2020-11-29 18:33

    Below 2 lines of code shows how to use Python List Comprehension to load 'java style' property file.

    split_properties=[line.split("=") for line in open('/<path_to_property_file>)]
    properties={key: value for key,value in split_properties }
    

    Please have a look at below post for details https://ilearnonlinesite.wordpress.com/2017/07/24/reading-property-file-in-python-using-comprehension-and-generators/

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