Pythonでプロパティファイルを読み取る方法

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

最初のステップは、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オブジェクトに格納されます。これは2つの値、つまりdatametaの名前付きタプルです。 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()メソッドを使用して、キーと対応するPropertyTuple値を含むTupleのコレクションを取得できます。

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

出力をkey=valueとして表示する必要があるため、次のコードを使用できます。

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