1. 程式人生 > >python讀取properties配置檔案

python讀取properties配置檔案

工作需要將Java專案的邏輯改為python執行,Java的很多配置檔案都是.properties的,檔案內容的格式是“鍵.鍵.鍵。。。=值”的格式例如A.B.C=value1,D.F=value2等。並且“#”用來注視。python沒有專門處理properties格式的包,只有處理標準的ini格式的包。所以需要自己寫一個python程式來處理。不說了上程式。

參考Robin_賓賓Python實用指令碼(1):讀取Properties檔案   URL:http://blog.sina.com.cn/s/blog_6a24f10901018lhn.html

主要在Robin_賓賓的基礎上,增加key.key.key=value的形式的支援

Util.py檔案:

class Properties(object):

    def __init__(self, fileName):
        self.fileName = fileName
        self.properties = {}

    def __getDict(self,strName,dictName,value):

        if(strName.find('.')>0):
            k = strName.split('.')[0]
            dictName.setdefault(k,{})
            return self.__getDict(strName[len(k)+1:],dictName[k],value)
        else:
            dictName[strName] = value
            return
    def getProperties(self):
        try:
            pro_file = open(self.fileName, 'Ur')
            for line in pro_file.readlines():
                line = line.strip().replace('\n', '')
                if line.find("#")!=-1:
                    line=line[0:line.find('#')]
                if line.find('=') > 0:
                    strs = line.split('=')
                    strs[1]= line[len(strs[0])+1:]
                    self.__getDict(strs[0].strip(),self.properties,strs[1].strip())
        except Exception, e:
            raise e
        else:
            pro_file.close()
        return self.properties

filename.properties檔案:

a.b.d=v1
a.c=v2
d.e=v3
f=v4

測試檔案text.py:
from Util import Properties
dictProperties=Properties("filename.properties").getProperties()
print dictProperties

輸出:
{'a': {'c': 'v2', 'b': {'d': 'v1'}}, 'd': {'e': 'v3'}, 'f': 'v4'}