国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python讀取properties配置文件操作示例

2020-01-04 15:27:42
字體:
來源:轉載
供稿:網友

本文實例講述了Python讀取properties配置文件操作。分享給大家供大家參考,具體如下:

工作需要將Java項目的邏輯改為python執行,Java的很多配置文件都是.properties的,文件內容的格式是“鍵.鍵.鍵。。。=值”的格式例如A.B.C=value1D.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.properties

filename.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程序設計有所幫助。


注:相關教程知識閱讀請移步到python教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 双江| 伊金霍洛旗| 垦利县| 定边县| 莎车县| 太仓市| 孙吴县| 锦州市| 康保县| 重庆市| 克什克腾旗| 班戈县| 灵宝市| 英吉沙县| 湖南省| 行唐县| 上饶市| 名山县| 乡城县| 阳春市| 墨脱县| 东兰县| 陆河县| 江安县| 钟山县| 苏州市| 武强县| 麻栗坡县| 治县。| 绥棱县| 通海县| 陵川县| 武隆县| 板桥市| 彰武县| 乌审旗| 阜平县| 府谷县| 望都县| 千阳县| 邛崃市|