本文實(shí)例講述了Python實(shí)現(xiàn)讀取Properties配置文件的方法。分享給大家供大家參考,具體如下:
JAVA本身提供了對(duì)于Properties文件操作的類,項(xiàng)目中的很多配置信息都是放在了Properties文件。但是Python并沒(méi)有提供操作Properties文件的庫(kù),所以,自己動(dòng)手寫個(gè)一個(gè)可以加載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 |
實(shí)際調(diào)用:
1
2
3
4
|
fileName = sys.path[ 0 ] + '\\'+ ' system.properties' p = Properties(fileName) properties = p.getProperties() print properties[Key] |
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
原文鏈接:http://blog.sina.com.cn/s/blog_6a24f10901018lhn.html