يمكننا استخدام وحدة الـ jproperties
لقراءة ملف الخصائص في Python. يحتوي ملف الخصائص على أزواج المفتاح والقيمة في كل سطر. يعمل العلامة (=) كفاصل بين المفتاح والقيمة. يُعامل السطر الذي يبدأ بـ # كتعليق.
تثبيت مكتبة jproperties
هذه الوحدة ليست جزءًا من التثبيت القياسي. يمكننا تثبيت وحدة jproperties باستخدام PIP.
# 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()
الخطوة الأولى هي استيراد كائن الخصائص إلى برنامج Python الخاص بنا وتثبيته.
with open('app-config.properties', 'rb') as config_file:
configs.load(config_file)
الخطوة التالية هي تحميل ملف الخصائص إلى كائن الخصائص الخاص بنا.
القراءة المُوصى بها: بيثون مع البيان
الآن ، يمكننا قراءة خاصية معينة باستخدام الطريقة get()
أو من خلال الفهرس. كائن الخصائص مشابه جدًا لـ Python Dictionary.
print(configs.get("DB_User"))
يتم تخزين القيمة في كائن PropertyTuple ، وهو tuple مسمى يحتوي على قيمتين - data و meta. تدعم خصائص 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.
# الناتج:
# ‘Key not found’، تم البحث باستخدام مفتاح البحث “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