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


 

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

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

這里參考前面一篇://www.jb51.net/article/137390.htm

主要在前文的基礎上,增加key.key.key=value的形式的支持

Util.py文件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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文件:

?
1
2
3
4
a.b.d=v1
a.c=v2
d.e=v3
f=v4

測試文件text.py:

?
1
2
3
from Util import Properties
dictProperties = Properties( "filename.properties" ).getProperties()
print dictProperties

輸出:

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

pip3 install properties #可以解決ModuleNotFoundError: No module named 'properties'問題

但是並沒有items模塊, 開源參考https://github.com/seequent/p...,官網參考https://propertiespy.readthed...

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM