本文實例講述了Python讀取properties配置文件操作。分享給大家供大家參考,具體如下:
工作需要將Java項目的邏輯改為python執行,Java的很多配置文件都是.properties的,文件內容的格式是“鍵.鍵.鍵。。。=值”的格式例如A.B.C=value1,D.F=value2等。并且“#”用來注視。python沒有專門處理properties格式的包,只有處理標準的ini格式的包。所以需要自己寫一個python程序來處理。不說了上程序。
主要在前文的基礎上,增加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.propertiesfilename.properties文件:
a.b.d=v1a.c=v2d.e=v3f=v4
測試文件text.py:
from Util import PropertiesdictProperties=Properties("filename.properties").getProperties()print dictProperties輸出:
{'a': {'c': 'v2', 'b': {'d': 'v1'}}, 'd': {'e': 'v3'}, 'f': 'v4'}
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答