Python を使用して Azure Data Lake Storage Gen2 でディレクトリとファイルを管理する
この記事では、階層型名前空間が有効になっているストレージ アカウントで、Python を使用してディレクトリとファイルを作成および管理する方法を示します。
ディレクトリとファイルのアクセス制御リスト (ACL) を取得、設定、および更新する方法については、「Azure Data Lake Storage Gen2 で Python を使用して ACL を管理する」を参照してください。
パッケージ (Python Package Index) | サンプル | API リファレンス | Gen1 から Gen2 へのマッピング | フィードバックを送る
前提条件
Azure サブスクリプション。 Azure 無料試用版の取得に関するページを参照してください。
階層型名前空間が有効になっているストレージ アカウント。 作成するには、こちらの手順に従います。
プロジェクトの設定
Python 向けの Azure Data Lake Storage クライアント ライブラリを、pip を使用してインストールします。
pip install azure-storage-file-datalake
次の import ステートメントを、コード ファイルの先頭に追加します。
import os, uuid, sys
from azure.storage.filedatalake import DataLakeServiceClient
from azure.core._match_conditions import MatchConditions
from azure.storage.filedatalake._models import ContentSettings
アカウントに接続する
この記事のスニペットを使用するには、ストレージ アカウントを表す DataLakeServiceClient インスタンスを作成する必要があります。
アカウント キーを使用して接続する
これはアカウントに接続する最も簡単な方法です。
この例では、アカウント キーを使用して DataLakeServiceClient インスタンスを作成します。
def initialize_storage_account(storage_account_name, storage_account_key):
try:
global service_client
service_client = DataLakeServiceClient(account_url="{}://{}.dfs.core.windows.net".format(
"https", storage_account_name), credential=storage_account_key)
except Exception as e:
print(e)
storage_account_name
プレースホルダーの値は、実際のストレージ アカウントの名前に置き換えます。storage_account_key
プレースホルダーの値は、実際のストレージ アカウントのアクセス キーに置き換えます。
Azure Active Directory (Azure AD) を使用して接続する
Python 用 Azure ID クライアント ライブラリを使用して、Azure AD でアプリケーションを認証できます。
この例では、クライアント ID、クライアント シークレット、およびテナント ID を使用して DataLakeServiceClient インスタンスを作成します。 これらの値を取得するには、「クライアント アプリケーションからの要求を承認するために Azure AD からトークンの取得する」を参照してください。
def initialize_storage_account_ad(storage_account_name, client_id, client_secret, tenant_id):
try:
global service_client
credential = ClientSecretCredential(tenant_id, client_id, client_secret)
service_client = DataLakeServiceClient(account_url="{}://{}.dfs.core.windows.net".format(
"https", storage_account_name), credential=credential)
except Exception as e:
print(e)
Note
その他の例については、Python 用 Azure ID クライアント ライブラリのドキュメントを参照してください。
コンテナーを作成する
コンテナーは、ファイルのファイル システムとして機能します。 FileSystemDataLakeServiceClient.create_file_system メソッドを呼び出すことによって作成できます。
この例では、my-file-system
という名前のコンテナーを作成します。
def create_file_system():
try:
global file_system_client
file_system_client = service_client.create_file_system(file_system="my-file-system")
except Exception as e:
print(e)
ディレクトリを作成する
FileSystemClient.create_directory メソッドを呼び出して、ディレクトリ参照を作成します。
この例では、my-directory
という名前のディレクトリをコンテナーに追加します。
def create_directory():
try:
file_system_client.create_directory("my-directory")
except Exception as e:
print(e)
ディレクトリの名前変更または移動
DataLakeDirectoryClient.rename_directory メソッドを呼び出して、ディレクトリの名前を変更するか、ディレクトリを移動します。 目的のディレクトリのパスをパラメーターに渡します。
この例では、サブディレクトリの名前を my-directory-renamed
に変更します。
def rename_directory():
try:
file_system_client = service_client.get_file_system_client(file_system="my-file-system")
directory_client = file_system_client.get_directory_client("my-directory")
new_dir_name = "my-directory-renamed"
directory_client.rename_directory(new_name=directory_client.file_system_name + '/' + new_dir_name)
except Exception as e:
print(e)
ディレクトリを削除する
DataLakeDirectoryClient.delete_directory メソッドを呼び出して、ディレクトリを削除します。
この例では、my-directory
という名前のディレクトリを削除します。
def delete_directory():
try:
file_system_client = service_client.get_file_system_client(file_system="my-file-system")
directory_client = file_system_client.get_directory_client("my-directory")
directory_client.delete_directory()
except Exception as e:
print(e)
ファイルをディレクトリにアップロードする
まず、DataLakeFileClient クラスのインスタンスを作成して、ターゲット ディレクトリにファイル参照を作成します。 DataLakeFileClient.append_data メソッドを呼び出して、ファイルをアップロードします。 DataLakeFileClient.flush_data メソッドを呼び出して、アップロードの完了を確認してください。
この例では、my-directory
という名前のディレクトリにテキスト ファイルをアップロードします。
def upload_file_to_directory():
try:
file_system_client = service_client.get_file_system_client(file_system="my-file-system")
directory_client = file_system_client.get_directory_client("my-directory")
file_client = directory_client.create_file("uploaded-file.txt")
local_file = open("C:\\file-to-upload.txt",'r')
file_contents = local_file.read()
file_client.append_data(data=file_contents, offset=0, length=len(file_contents))
file_client.flush_data(len(file_contents))
except Exception as e:
print(e)
ヒント
ファイル サイズが大きい場合は、コードで DataLakeFileClient.append_data メソッドを複数回呼び出す必要があります。 代わりに DataLakeFileClient.upload_data メソッドを使用することを検討してください。 この方法により、1 回の呼び出しでファイル全体をアップロードできます。
大きなファイルをディレクトリにアップロードする
DataLakeFileClient.upload_data メソッドを使用して大きなファイルをアップロードします。DataLakeFileClient.append_data メソッドを複数回呼び出す必要はありません。
def upload_file_to_directory_bulk():
try:
file_system_client = service_client.get_file_system_client(file_system="my-file-system")
directory_client = file_system_client.get_directory_client("my-directory")
file_client = directory_client.get_file_client("uploaded-file.txt")
local_file = open("C:\\file-to-upload.txt",'r')
file_contents = local_file.read()
file_client.upload_data(file_contents, overwrite=True)
except Exception as e:
print(e)
ディレクトリからダウンロードする
書き込み用にローカル ファイルを開きます。 次に、ダウンロードするファイルを表す DataLakeFileClient インスタンスを作成します。 DataLakeFileClient.read_file を呼び出して、ファイルからバイトを読み取り、そのバイトをローカル ファイルに書き込みます。
def download_file_from_directory():
try:
file_system_client = service_client.get_file_system_client(file_system="my-file-system")
directory_client = file_system_client.get_directory_client("my-directory")
local_file = open("C:\\file-to-download.txt",'wb')
file_client = directory_client.get_file_client("uploaded-file.txt")
download = file_client.download_file()
downloaded_bytes = download.readall()
local_file.write(downloaded_bytes)
local_file.close()
except Exception as e:
print(e)
ディレクトリの内容を一覧表示する
FileSystemClient.get_paths メソッドを呼び出してディレクトリの内容を一覧表示し、結果を列挙します。
この例では、my-directory
という名前のディレクトリにある各サブディレクトリとファイルのパスを出力します。
def list_directory_contents():
try:
file_system_client = service_client.get_file_system_client(file_system="my-file-system")
paths = file_system_client.get_paths(path="my-directory")
for path in paths:
print(path.name + '\n')
except Exception as e:
print(e)