2017-01-31 6 views
0

私はPythonファイルから使用したいいくつかのキーと値を保存する.propertiesファイルを持っています。.propertiesファイルでPYTHONを使用して定義されたプロパティの解析と使用

マイtest.propertiesファイルは、そのようなものです:

attribute1=username 
attribute2=address 
attribute3=class 

私のような何かをするとき、私はそのようにPythonのファイルからこれらの属性にアクセスしたいと思います。今

attribute1 = "tom123" 
attribute2 = "5 Smith Street" 
attribute3 = "402" 

をしかし、私はpythonでconfig.propertiesファイルをインポートし、定義されたプロパティを使用して起動する方法が不思議です。 ご協力いただきありがとうございます。

答えて

0

あなたはこのようなPythonの辞書にあなたの設定ファイルを読み込むことができます。

config = {} 

with open('config.properties', 'r',) as f: 
    for line in f.readlines(): 
     line = line.strip() # removes the newline characters 
     parts = line.split("=") # creates a (key, value) tuple 
     key = parts[0] 
     value = parts[1] 
     config[key] = value 

attribute1 = config['attribute1'] 
attribute2 = config['attribute2'] 
attribute3 = config['attribute3'] 
関連する問題