本文實例講述了Python實現讀取Properties配置文件的方法。分享給大家供大家參考,具體如下:
JAVA本身提供了對于Properties文件操作的類,項目中的很多配置信息都是放在了Properties文件。但是Python并沒有提供操作Properties文件的庫,所以,自己動手寫個一個可以加載Properties文件的腳本。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
class Properties: fileName = '' def __init__( self , fileName): self .fileName = fileName def getProperties( self ): try : pro_file = open ( self .fileName, 'r' ) properties = {} for line in pro_file: if line.find( '=' ) > 0 : strs = line.replace( '\n' , ' ').split(' = ') properties[strs[ 0 ]] = strs[ 1 ] except Exception, e: raise e else : pro_file.close() return properties |
實際調用:
1
2
3
4
|
fileName = sys.path[ 0 ] + '\\'+ ' system.properties' p = Properties(fileName) properties = p.getProperties() print properties[Key] |
希望本文所述對大家Python程序設計有所幫助。
原文鏈接:http://blog.sina.com.cn/s/blog_6a24f10901018lhn.html