Python を使用して Azure Data Lake Storage Gen2 でディレクトリとファイルを管理する

この記事では、階層型名前空間が有効になっているストレージ アカウントで、Python を使用してディレクトリとファイルを作成および管理する方法を示します。

ディレクトリとファイルのアクセス制御リスト (ACL) を取得、設定、および更新する方法については、「Azure Data Lake Storage Gen2 で Python を使用して ACL を管理する」を参照してください。

パッケージ (PyPi) | サンプル | API リファレンス | Gen1 から Gen2 へのマッピング | フィードバックを送る

前提条件

プロジェクトの設定

このセクションでは、Python 用 Azure Data Lake Storage クライアント ライブラリを操作するためのプロジェクトの準備について説明します。

プロジェクト ディレクトリから、pip install コマンドを使用して、Azure Data Lake Storage と Azure ID のクライアント ライブラリのパッケージをインストールします。 Azure サービスへのパスワードレス接続には、azure-identity パッケージが必要です。

pip install azure-storage-file-datalake azure-identity

次にコード ファイルを開き、必要な import ステートメントを追加します。 この例では、以下を .py ファイルに追加します。

import os
from azure.storage.filedatalake import (
    DataLakeServiceClient,
    DataLakeDirectoryClient,
    FileSystemClient
)
from azure.identity import DefaultAzureCredential

Note

Data Lake Storage のマルチプロトコル アクセスでは、アプリケーションは BLOB API と Data Lake Storage Gen2 API の両方を使用して、階層型名前空間 (HNS) が有効なストレージ アカウント内のデータを操作できます。 ディレクトリ操作や ACL など、Data Lake Storage Gen2 に固有の機能を使用する場合は、この記事に示すように Data Lake Storage Gen2 API を使用します。

特定のシナリオで使用する API を選択する場合は、ワークロードとアプリケーションのニーズを、既知の問題HNS がワークロードとアプリケーションに与える影響と一緒に考慮してください。

データ リソースへのアクセスを認可して接続する

この記事のコード例を使用するには、ストレージ アカウントを表す認可済みの DataLakeServiceClient インスタンスを作成する必要があります。 Microsoft Entra ID、アカウント アクセス キー、または Shared Access Signature (SAS) を使って、DataLakeServiceClient オブジェクトを承認できます。

Python 用 Azure ID クライアント ライブラリを使って、Microsoft Entra ID でアプリケーションを認証できます。

DataLakeServiceClient クラスのインスタンスを作成し、DefaultAzureCredential オブジェクトを渡します。

def get_service_client_token_credential(self, account_name) -> DataLakeServiceClient:
    account_url = f"https://{account_name}.dfs.core.windows.net"
    token_credential = DefaultAzureCredential()

    service_client = DataLakeServiceClient(account_url, credential=token_credential)

    return service_client

DefaultAzureCredential を使用してデータへのアクセスを承認する方法の詳細については、「概要: Azure SDK for Python を使用して Azure サービスに対して Python アプリを認証する方法」を参照してください。

コンテナーを作成する

コンテナーは、ファイルのファイル システムとして機能します。 次のメソッドを使用して、コンテナーを作成できます。

次のコード例では、コンテナーを作成し、後で使用するために FileSystemClient オブジェクトを返します。

def create_file_system(self, service_client: DataLakeServiceClient, file_system_name: str) -> FileSystemClient:
    file_system_client = service_client.create_file_system(file_system=file_system_name)

    return file_system_client

ディレクトリを作成する

次のメソッドを使用して、コンテナー内にディレクトリ参照を作成できます。

次のコード例では、コンテナーにディレクトリを追加し、後で使用するために DataLakeDirectoryClient オブジェクトを返します。

def create_directory(self, file_system_client: FileSystemClient, directory_name: str) -> DataLakeDirectoryClient:
    directory_client = file_system_client.create_directory(directory_name)

    return directory_client

ディレクトリの名前変更または移動

次のメソッドを使用して、ディレクトリの名前の変更または移動を行うことができます。

new_name 引数に新しいディレクトリ名を含むパスを渡します。 値は次の形式である必要があります: {ファイルシステメム}/{ディレクトリ}/{サブディレクトリ}。

次のコード例は、サブディレクトリの名前の変更方法を示しています。

def rename_directory(self, directory_client: DataLakeDirectoryClient, new_dir_name: str):
    directory_client.rename_directory(
        new_name=f"{directory_client.file_system_name}/{new_dir_name}")

ファイルをディレクトリにアップロードする

次のメソッドを使用して、新規または既存のファイルにコンテンツをアップロードできます。

次のコード例は、upload_data メソッドを使用してファイルをディレクトリにアップロードする方法を示しています。

def upload_file_to_directory(self, directory_client: DataLakeDirectoryClient, local_path: str, file_name: str):
    file_client = directory_client.get_file_client(file_name)

    with open(file=os.path.join(local_path, file_name), mode="rb") as data:
        file_client.upload_data(data, overwrite=True)

このメソッドを使用してコンテンツを作成して新しいファイルにアップロードすることも、overwrite 引数を True に設定して既存のファイルを上書きすることもできます。

ファイルにデータを追加する

次のメソッドを使用して、ファイルに追加するデータをアップロードできます。

次のコード例は、これらの手順を使用してファイルの末尾にデータを追加する方法を示しています。

  • 操作しているファイル リソースを表す DataLakeFileClient オブジェクトを作成します。
  • append_data メソッドを使用してファイルにデータをアップロードします。
  • flush_data メソッドを呼び出し、先にアップロード済みのデータをファイルに書き込むことで、アップロードを完了します。
def append_data_to_file(self, directory_client: DataLakeDirectoryClient, file_name: str):
    file_client = directory_client.get_file_client(file_name)
    file_size = file_client.get_file_properties().size
    
    data = b"Data to append to end of file"
    file_client.append_data(data, offset=file_size, length=len(data))

    file_client.flush_data(file_size + len(data))

このメソッドでは、データをファイルに追加することだけが可能で、操作は要求あたり 4,000 MiB に制限されます。

ディレクトリからダウンロードする

次のコード例は、これらの手順を使用して、ディレクトリからローカル ファイルへとファイルをダウンロードする方法を示しています。

  • ダウンロードしたいファイルを表す DataLakeFileClient オブジェクトを作成します。
  • 書き込み用にローカル ファイルを開きます。
  • DataLakeFileClient.download_file メソッドを呼び出してファイルから読み取りを行った後に、そのデータをローカル ファイルに書き込みます。
def download_file_from_directory(self, directory_client: DataLakeDirectoryClient, local_path: str, file_name: str):
    file_client = directory_client.get_file_client(file_name)

    with open(file=os.path.join(local_path, file_name), mode="wb") as local_file:
        download = file_client.download_file()
        local_file.write(download.readall())
        local_file.close()

ディレクトリの内容を一覧表示する

次のメソッドを使用し結果を列挙することで、ディレクトリのコンテンツを一覧表示できます。

結果内のパスの列挙は、値のフェッチ中にサービスに対して複数の要求を行う場合があります。

次のコード例では、ディレクトリにある各サブディレクトリとファイルのパスを出力します。

def list_directory_contents(self, file_system_client: FileSystemClient, directory_name: str):
    paths = file_system_client.get_paths(path=directory_name)

    for path in paths:
        print(path.name + '\n')

ディレクトリを削除する

次のメソッドを使用して、ディレクトリを削除できます。

次のコード例は、ディレクトリを削除する方法を示しています。

def delete_directory(self, directory_client: DataLakeDirectoryClient):
    directory_client.delete_directory()

関連項目