Properties file in python (similar to Java Properties)

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

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

propertyName1=propertyValue1
propertyName2=propertyValue2
...
propertyNam         


        
25条回答
  •  失恋的感觉
    2020-11-29 18:34

    You can use the following function, which is the modified code of @mvallebr. It respects the properties file comments, ignores empty new lines, and allows retrieving a single key value.

    def getProperties(propertiesFile ="/home/memin/.config/customMemin/conf.properties", key=''):
        """
        Reads a .properties file and returns the key value pairs as dictionary.
        if key value is specified, then it will return its value alone.
        """
        with open(propertiesFile) as f:
            l = [line.strip().split("=") for line in f.readlines() if not line.startswith('#') and line.strip()]
            d = {key.strip(): value.strip() for key, value in l}
    
            if key:
                return d[key]
            else:
                return d
    

提交回复
热议问题