איך לקרוא קובץ תכונות ב-Python?

ניתן להשתמש במודול jproperties כדי לקרוא קובץ מאפיינים בפייתון. קובץ מאפיינים מכיל זוגות מפתח-ערך בכל שורה. הסימן שווה (=) עובד כמפריד בין המפתח והערך. שורה שמתחילה ב-# מטופלת כהערה.

התקנת ספריית jproperties

מודול זה אינו חלק מההתקנה התקנית. ניתן להתקין את מודול jproperties באמצעות PIP.

# pip install jproperties

קריאת קובץ מאפיינים בפייתון

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()

השלב הראשון הוא לייבא את אובייקט המאפיינים לתוך התוכנית שלנו בפייתון וליצור אותו.

with open('app-config.properties', 'rb') as config_file:
    configs.load(config_file)

השלב הבא הוא לטעון את קובץ המאפיינים לתוך אובייקט המאפיינים שלנו.

קריאה מומלצת: הצהרת Python

עכשיו, אנו יכולים לקרוא מאפיין ספציפי באמצעות שימוש בשיטת get() או דרך האינדקס. אובייקט המאפיינים דומה מאוד ל־מילון Python.

print(configs.get("DB_User"))  
הערך מאוחסן באובייקט PropertyTuple, שהוא tuple בעל שני ערכים - data ו־meta. התמיכה במאפייני תכונות כוללת גם מטא-נתונים, אך איננו מתעניינים בזה כאן. 

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