Pythonでプロパティファイルを読み込む方法は?

私たちはjpropertiesモジュールを使用して、Pythonでプロパティファイルを読み込むことができます。プロパティファイルには、各行にキーと値のペアが含まれています。イコール(=)は、キーと値の間の区切りとして機能します。#で始まる行はコメントとして扱われます。

jpropertiesライブラリをインストールする

このモジュールは標準のインストールに含まれていません。PIPを使用してjpropertiesモジュールをインストールすることができます。

# pip install jproperties

Pythonでプロパティファイルを読み込む

私は私たちの例のためにプロパティファイルを作成しました。app-config.propertiesです。

# Database Credentials
DB_HOST=localhost
DB_SCHEMA=Test
DB_User=root
DB_PWD=root@neon

最初のステップは、PropertiesオブジェクトをPythonプログラムにインポートし、それをインスタンス化することです。

from jproperties import Properties

configs = Properties()

次のステップは、プロパティファイルをPropertiesオブジェクトにロードすることです。

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

おすすめの読み物:Pythonのwith文

Now, we can use the get()メソッドまたはインデックスを介して特定のプロパティを読み取ることができます。Propertiesオブジェクトは、Pythonの辞書に非常に似ています。

値はPropertyTupleオブジェクトに格納されており、これはデータとメタデータの2つの値を持つ名前付きタプルです。jpropertiesはプロパティのメタデータもサポートしていますが、今回はそれに興味はありません。

print(configs.get("DB_User"))  
# PropertyTuple(data='root', meta={})

print(f'Database User: {configs.get("DB_User").data}')  
# Database User: root

print(f'Database Password: {configs["DB_PWD"].data}')  
# Database Password: root@neon

プロパティの数を取得するために、len()関数を使用することができます。

print(f'Properties Count: {len(configs)}')  
# Properties Count: 4

もし鍵が存在しなかったら、どうなりますか? (Moshi kagi ga sonzai shinakattara, dou narimasu ka?)

もしキーが存在しなければ、get()メソッドはNoneを返します。

random_value = configs.get("Random_Key")
print(random_value)  # None

しかし、インデックスを使用する場合、KeyErrorが発生します。その場合、try-exceptブロックを使用してこの例外を処理する方が良いです。

try:
    random_value = configs["Random_Key"]
    print(random_value)
except KeyError as ke:
    print(f'{ke}, lookup key was "Random_Key"')

# Output:
# 'Key not found', lookup key was "Random_Key"

全てのプロパティを印刷します。

items()メソッドを使用することで、キーと対応するPropertyTupleの値を含むタプルのコレクションを取得することができます。

items_view = configs.items()
print(type(items_view))

for item in items_view:
    print(item)

出力:

<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={}))

出力としてkey=valueを印刷するために、次のコードを使用することができます。

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']

Pythonのプロパティファイルを辞書に読み込む

プロパティファイルは辞書と同じです。だから、プロパティファイルを辞書に読み込むのは一般的な手法です。手順は上記と同様ですが、要素を辞書に追加するための反復コードの変更が異なります。

db_configs_dict = {}

for item in items_view:
    db_configs_dict[item[0]] = item[1].data

print(db_configs_dict)
# {'DB_HOST': 'localhost', 'DB_SCHEMA': 'Test', 'DB_User': 'root', 'DB_PWD': 'root@neon'}

参照元:PyPI jproperties ページ

コメントを残す 0

Your email address will not be published. Required fields are marked *