我們可以使用jproperties
模塊來在Python中讀取屬性文件。 屬性文件中的每行都包含鍵-值對。 等號(=)作為鍵和值之間的分隔符。 以#開頭的行被視為註釋。
安裝jproperties庫
此模塊不是標準安裝的一部分。 我們可以使用PIP安裝jproperties模塊。
# pip install jproperties
在Python中讀取屬性文件
I have created a properties file for our example: app-config.properties.
# Database Credentials
DB_HOST=localhost
DB_SCHEMA=Test
DB_User=root
DB_PWD=root@neon
# 數據庫 憑據
from jproperties import Properties
configs = Properties()
第一步是將Properties對象導入我們的Python程序並對其進行實例化。
with open('app-config.properties', 'rb') as config_file:
configs.load(config_file)
下一步是將屬性文件加載到我們的Properties對象中。
推薦閱讀: Python with語句
現在,我們可以使用get()
方法或通過索引來讀取特定屬性。Properties物件非常類似於Python字典。
print(configs.get("DB_User"))
值存儲在PropertyTuple物件中,該物件是兩個值的具名元組 - 數據和元數據。 jproperties還支持屬性元數據,但我們這裡不感興趣。
print(f'Database User: {configs.get("DB_User").data}')
# PropertyTuple(data='root', meta={})
print(f'Database Password: {configs["DB_PWD"].data}')
# Database User: root
# Database Password: root@neon
print(f'Properties Count: {len(configs)}')
我們可以使用len() 函數來獲取屬性的計數。
# Properties Count: 4
random_value = configs.get("Random_Key")
print(random_value) 如果鍵不存在,get()方法將返回None。
# None
try:
random_value = configs["Random_Key"]
print(random_value)
except KeyError as ke:
print(f'{ke}, lookup key was "Random_Key"')
但是,如果我們使用索引,則會引發KeyError
。在這種情況下,最好使用try-except區塊來處理此異常。
# 輸出:
# ‘未找到鍵’,查找鍵為”Random_Key”
items_view = configs.items()
print(type(items_view))
for item in items_view:
print(item)
我們可以使用items()方法獲取一個Tuple的集合,其中包含鍵和相應的PropertyTuple值。
<class 'collections.abc.ItemsView'>
('DB_HOST', PropertyTuple(data='localhost', meta={}))
('DB_SCHEMA', PropertyTuple(data='Test', meta={}))
('DB_User', PropertyTuple(data='root', meta={}))
('DB_PWD', PropertyTuple(data='root@neon', meta={}))
輸出:
for item in items_view:
print(item[0], '=', item[1].data)
由於我們希望將鍵=值打印為輸出,我們可以使用以下代碼。
DB_HOST = localhost
DB_SCHEMA = Test
DB_User = root
DB_PWD = root@neon
輸出:
from jproperties import Properties
configs = Properties()
with open('app-config.properties', 'rb') as config_file:
configs.load(config_file)
items_view = configs.items()
list_keys = []
for item in items_view:
list_keys.append(item[0])
print(list_keys)
這是一個完整的程序,用於讀取屬性文件並創建所有鍵的列表。
# [‘DB_HOST’, ‘DB_SCHEMA’, ‘DB_User’, ‘DB_PWD’]
A properties file is the same as a dictionary. So, it’s a common practice to read the properties file into a dictionary. The steps are similar to above, except for the change in the iteration code to add the elements to a dictionary.
db_configs_dict = {}
for item in items_view:
db_configs_dict[item[0]] = item[1].data
print(db_configs_dict)
Python 讀取屬性文件並轉換為字典
# {‘DB_HOST’: ‘localhost’, ‘DB_SCHEMA’: ‘Test’, ‘DB_User’: ‘root’, ‘DB_PWD’: ‘root@neon’}
Source:
https://www.digitalocean.com/community/tutorials/python-read-properties-file