使用 Python 來管理 Azure Data Lake Storage Gen2 中的目錄和檔案

此文章說明如何使用 Python,在具有階層命名空間的儲存體帳戶中建立及管理目錄和檔案。

若要了解如何取得、設定及更新目錄和檔案的存取控制清單 (ACL),請參閱使用 Python 管理 Azure Data Lake Storage Gen2 中的 ACL

套件 (PyPi) | 範例 | API 參考 | Gen1 對 Gen2 對應 | 提供意見反應

必要條件

設定您的專案

本節會引導您準備專案以搭配適用於 Python 的 Azure Data Lake Storage 用戶端程式庫使用。

從您的專案目錄中,使用 pip install 命令安裝 Azure Data Lake Storage 和 Azure 身分識別用戶端程式庫的套件。 需要 Azure 身分識別套件才能對 Azure 服務進行無密碼連線。

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

然後開啟程式碼檔案,並新增必要的匯入陳述式。 在此範例中,我們會將下列內容新增至 .py 檔案:

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

注意

Data Lake 儲存體 上的多重通訊協定存取可讓應用程式同時使用 Blob API 和 Data Lake 儲存體 Gen2 API,以使用已啟用階層命名空間 (HNS) 的記憶體帳戶中的數據。 使用 Data Lake 儲存體 Gen2 特有的功能時,例如目錄作業和 ACL,請使用 Data Lake 儲存體 Gen2 API,如本文所示。

選擇要在指定案例中使用的 API 時,請考慮應用程式的工作負載和需求,以及 HNS 對工作負載和應用程式的已知問題和影響。

授權存取權並連線到資料資源

若要使用此文章中的程式碼範例,您必須建立代表儲存體帳戶的已授權 DataLakeServiceClient 執行個體。 您可以使用 Microsoft Entra ID、帳戶存取密鑰或共用存取簽章 (SAS) 來授權 DataLakeServiceClient 物件。

您可以使用適用於 Python 的 Azure 身分識別用戶端程式庫,以 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 向 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 引數中傳遞包含新目錄名稱的路徑。 值必須採用下列格式:{filesystem}/{directory}/{subdirectory}。

下列程式碼範例示範如何重新命名子目錄:

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

使用此方法時,資料只能附加至檔案,且作業限制為每個要求 4000 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()

另請參閱