選項
首頁首頁 Skill 開發營運和 CI/CD azure-storage-file-datalake-py

azure-storage-file-datalake-py

microsoft/skills microsoft/skills

使用 Python SDK 管理 Azure Data Lake Storage Gen2,支援分層檔案系統、大資料分析以及檔案/目錄操作。

...展開全部
0
更新時間 2026-09-16

Azure Data Lake Storage Gen2 Python SDK

面向大資料分析工作負載的分層檔案系統。

安裝

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

環境變數

AZURE_STORAGE_ACCOUNT_URL=https://<account>.dfs.core.windows.net  # 所有身份驗證方法均必需
AZURE_TOKEN_CREDENTIALS=prod # 僅在生產環境中使用 DefaultAzureCredential 時必需
</account>

身份驗證與生命週期管理

🔑 以下所有程式碼示例均遵循兩條規則:

  1. 優先使用 DefaultAzureCredential 它在本地(Azure CLI / VS Code / Developer CLI)和 Azure(託管標識、工作負載標識)中均能正常工作,且無需更改程式碼。請避免使用連線字串、賬戶/API 金鑰——它們會繞過 Entra 審計和輪換機制。
    • 本地開發:DefaultAzureCredential 可直接使用。
    • 生產環境:設定 AZURE_TOKEN_CREDENTIALS=prod(或 AZURE_TOKEN_CREDENTIALS=<specific_credential></specific_credential>),以將憑據鏈限制為生產環境安全的憑據。
  2. 將每個客戶端包裝在上下文管理器中,以便確定性地釋放 HTTP 傳輸層、套接字和令牌快取:
    • 同步:with <client>(...) as client:</client>
    • 非同步:async with <client>(...) as client:</client> 以及 async with DefaultAzureCredential() as credential:(來自 azure.identity.aio

程式碼片段可能會簡化此設定,但生產程式碼應始終遵循這兩條規則。

from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.storage.filedatalake import DataLakeServiceClient

# 本地開發:DefaultAzureCredential。生產環境:設定 AZURE_TOKEN_CREDENTIALS=prod 或 AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# 或者在生產環境中直接使用特定憑據:
# 請參閱 https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
account_url = "https://<account>.dfs.core.windows.net"

with DataLakeServiceClient(account_url=account_url, credential=credential) as service_client:
    # 在此處使用 service_client(請參閱以下各節瞭解操作方法)
    ...
</account></specific_credential>

客戶端層級結構

客戶端用途
`DataLakeServiceClient`賬戶級操作
`FileSystemClient`容器(檔案系統)操作
`DataLakeDirectoryClient`目錄操作
`DataLakeFileClient`檔案操作

檔案系統操作

# 建立檔案系統(容器)
file_system_client = service_client.create_file_system("myfilesystem")

# 獲取現有檔案系統
file_system_client = service_client.get_file_system_client("myfilesystem")

# 刪除
service_client.delete_file_system("myfilesystem")

# 列出檔案系統
for fs in service_client.list_file_systems():
    print(fs.name)

目錄操作

file_system_client = service_client.get_file_system_client("myfilesystem")

# 建立目錄
directory_client = file_system_client.create_directory("mydir")

# 建立巢狀目錄
directory_client = file_system_client.create_directory("path/to/nested/dir")

# 獲取目錄客戶端
directory_client = file_system_client.get_directory_client("mydir")

# 刪除目錄
directory_client.delete_directory()

# 重新命名/移動目錄
directory_client.rename_directory(new_name="myfilesystem/newname")

檔案操作

上傳檔案

# 獲取檔案客戶端
file_client = file_system_client.get_file_client("path/to/file.txt")

# 從本地檔案上傳
with open("local-file.txt", "rb") as data:
    file_client.upload_data(data, overwrite=True)

# 上傳位元組資料
file_client.upload_data(b"Hello, Data Lake!", overwrite=True)

# 追加資料(適用於大檔案)
file_client.append_data(data=b"chunk1", offset=0, length=6)
file_client.append_data(data=b"chunk2", offset=6, length=6)
file_client.flush_data(12)  # 提交資料

下載檔案

file_client = file_system_client.get_file_client("path/to/file.txt")

# 下載所有內容
download = file_client.download_file()
content = download.readall()

# 下載到檔案
with open("downloaded.txt", "wb") as f:
    download = file_client.download_file()
    download.readinto(f)

# 下載指定範圍
download = file_client.download_file(offset=0, length=100)

刪除檔案

file_client.delete_file()

列出內容

# 列出路徑(檔案和目錄)
for path in file_system_client.get_paths():
    print(f"{'DIR' if path.is_directory else 'FILE'}: {path.name}")

# 列出目錄中的路徑
for path in file_system_client.get_paths(path="mydir"):
    print(path.name)

# 遞迴列出
for path in file_system_client.get_paths(path="mydir", recursive=True):
    print(path.name)

檔案/目錄屬性

# 獲取屬性
properties = file_client.get_file_properties()
print(f"Size: {properties.size}")
print(f"Last modified: {properties.last_modified}")

# 設定後設資料
file_client.set_metadata(metadata={"processed": "true"})

訪問控制 (ACL)

# 獲取 ACL
acl = directory_client.get_access_control()
print(f"Owner: {acl['owner']}")
print(f"Permissions: {acl['permissions']}")

# 設定 ACL
directory_client.set_access_control(
    owner="user-id",
    permissions="rwxr-x---"
)

# 更新 ACL 條目
from azure.storage.filedatalake import AccessControlChangeResult
directory_client.update_access_control_recursive(
    acl="user:user-id:rwx"
)

非同步客戶端

from azure.storage.filedatalake.aio import DataLakeServiceClient
from azure.identity.aio import DefaultAzureCredential

async def datalake_operations():
    async with DefaultAzureCredential() as credential:
        async with DataLakeServiceClient(
            account_url="https://<account>.dfs.core.windows.net",
            credential=credential
        ) as service_client:
            file_system_client = service_client.get_file_system_client("myfilesystem")
            file_client = file_system_client.get_file_client("test.txt")

            await file_client.upload_data(b"async content", overwrite=True)

            download = await file_client.download_file()
            content = await download.readall()

import asyncio
asyncio.run(datalake_operations())
</account>

最佳實踐

  1. 選擇同步或非同步,並保持一致。 請勿在同一呼叫路徑中混合使用 azure.storage.filedatalake 同步客戶端與 azure.storage.filedatalake.aio 非同步客戶端。請在每個模組中選擇一個模式。
  2. 始終對客戶端和非同步憑據使用上下文管理器。 將每個客戶端包裝在 with DataLakeServiceClient(...) as client:(同步)或 async with DataLakeServiceClient(...) as client:(非同步)中。對於來自 azure.identity.aio 的非同步 DefaultAzureCredential,也請使用 async with credential:,以便清理令牌和傳輸層。
  3. 使用 DefaultAzureCredential 實現本地開發和 Azure 之間的可移植身份驗證(儘可能避免使用連線字串/API 金鑰)。
  4. 使用分層名稱空間 以實現檔案系統語義
  5. 使用 append_data + flush_data 進行大檔案上傳
  6. 在目錄級別設定 ACL 並繼承給子級
  7. 使用非同步客戶端 處理高吞吐量場景
  8. 使用 get_paths 配合 recursive=True 進行完整的目錄列表
  9. 設定後設資料 以自定義檔案屬性
  10. 考慮使用 Blob API 處理簡單的物件儲存用例
在 GitHub 上查看
---
name: azure-storage-file-datalake-py
description: Manage Azure Data Lake Storage Gen2 with Python SDK for hierarchical file systems, big data analytics, and file/directory operations.
license: MIT
---

# Azure Data Lake Storage Gen2 SDK for Python

Hierarchical file system for big data analytics workloads.

## Installation

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

## Environment Variables

```bash
AZURE_STORAGE_ACCOUNT_URL=https://<account>.dfs.core.windows.net  # Required for all auth methods
AZURE_TOKEN_CREDENTIALS=prod # Required only if DefaultAzureCredential is used in production
```

## Authentication & Lifecycle

> **🔑 Two rules apply to every code sample below:**
>
> 1. **Prefer `DefaultAzureCredential`.** It works locally (Azure CLI / VS Code / Developer CLI) and in Azure (managed identity, workload identity) with no code change. Avoid connection strings, account/API keys — they bypass Entra audit and rotation.
>    - Local dev: `DefaultAzureCredential` works as-is.
>    - Production: set `AZURE_TOKEN_CREDENTIALS=prod` (or `AZURE_TOKEN_CREDENTIALS=<specific_credential>`) to constrain the credential chain to production-safe credentials.
> 2. **Wrap every client in a context manager** so HTTP transports, sockets, and token caches are released deterministically:
>    - Sync: `with <Client>(...) as client:`
>    - Async: `async with <Client>(...) as client:` **and** `async with DefaultAzureCredential() as credential:` (from `azure.identity.aio`)
>
> Snippets may abbreviate this setup, but production code should always follow both rules.

```python
from azure.identity import DefaultAzureCredential, ManagedIdentityCredential
from azure.storage.filedatalake import DataLakeServiceClient

# Local dev: DefaultAzureCredential. Production: set AZURE_TOKEN_CREDENTIALS=prod or AZURE_TOKEN_CREDENTIALS=<specific_credential>
credential = DefaultAzureCredential(require_envvar=True)
# Or use a specific credential directly in production:
# See https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes
# credential = ManagedIdentityCredential()
account_url = "https://<account>.dfs.core.windows.net"

with DataLakeServiceClient(account_url=account_url, credential=credential) as service_client:
    # Use service_client here (see following sections for operations)
    ...
```

## Client Hierarchy

| Client | Purpose |
|--------|---------|
| `DataLakeServiceClient` | Account-level operations |
| `FileSystemClient` | Container (file system) operations |
| `DataLakeDirectoryClient` | Directory operations |
| `DataLakeFileClient` | File operations |

## File System Operations

```python
# Create file system (container)
file_system_client = service_client.create_file_system("myfilesystem")

# Get existing
file_system_client = service_client.get_file_system_client("myfilesystem")

# Delete
service_client.delete_file_system("myfilesystem")

# List file systems
for fs in service_client.list_file_systems():
    print(fs.name)
```

## Directory Operations

```python
file_system_client = service_client.get_file_system_client("myfilesystem")

# Create directory
directory_client = file_system_client.create_directory("mydir")

# Create nested directories
directory_client = file_system_client.create_directory("path/to/nested/dir")

# Get directory client
directory_client = file_system_client.get_directory_client("mydir")

# Delete directory
directory_client.delete_directory()

# Rename/move directory
directory_client.rename_directory(new_name="myfilesystem/newname")
```

## File Operations

### Upload File

```python
# Get file client
file_client = file_system_client.get_file_client("path/to/file.txt")

# Upload from local file
with open("local-file.txt", "rb") as data:
    file_client.upload_data(data, overwrite=True)

# Upload bytes
file_client.upload_data(b"Hello, Data Lake!", overwrite=True)

# Append data (for large files)
file_client.append_data(data=b"chunk1", offset=0, length=6)
file_client.append_data(data=b"chunk2", offset=6, length=6)
file_client.flush_data(12)  # Commit the data
```

### Download File

```python
file_client = file_system_client.get_file_client("path/to/file.txt")

# Download all content
download = file_client.download_file()
content = download.readall()

# Download to file
with open("downloaded.txt", "wb") as f:
    download = file_client.download_file()
    download.readinto(f)

# Download range
download = file_client.download_file(offset=0, length=100)
```

### Delete File

```python
file_client.delete_file()
```

## List Contents

```python
# List paths (files and directories)
for path in file_system_client.get_paths():
    print(f"{'DIR' if path.is_directory else 'FILE'}: {path.name}")

# List paths in directory
for path in file_system_client.get_paths(path="mydir"):
    print(path.name)

# Recursive listing
for path in file_system_client.get_paths(path="mydir", recursive=True):
    print(path.name)
```

## File/Directory Properties

```python
# Get properties
properties = file_client.get_file_properties()
print(f"Size: {properties.size}")
print(f"Last modified: {properties.last_modified}")

# Set metadata
file_client.set_metadata(metadata={"processed": "true"})
```

## Access Control (ACL)

```python
# Get ACL
acl = directory_client.get_access_control()
print(f"Owner: {acl['owner']}")
print(f"Permissions: {acl['permissions']}")

# Set ACL
directory_client.set_access_control(
    owner="user-id",
    permissions="rwxr-x---"
)

# Update ACL entries
from azure.storage.filedatalake import AccessControlChangeResult
directory_client.update_access_control_recursive(
    acl="user:user-id:rwx"
)
```

## Async Client

```python
from azure.storage.filedatalake.aio import DataLakeServiceClient
from azure.identity.aio import DefaultAzureCredential

async def datalake_operations():
    async with DefaultAzureCredential() as credential:
        async with DataLakeServiceClient(
            account_url="https://<account>.dfs.core.windows.net",
            credential=credential
        ) as service_client:
            file_system_client = service_client.get_file_system_client("myfilesystem")
            file_client = file_system_client.get_file_client("test.txt")
            
            await file_client.upload_data(b"async content", overwrite=True)
            
            download = await file_client.download_file()
            content = await download.readall()

import asyncio
asyncio.run(datalake_operations())
```

## Best Practices

1. **Pick sync OR async and stay consistent.** Do not mix `azure.storage.filedatalake` sync clients with `azure.storage.filedatalake.aio` async clients in the same call path. Choose one mode per module.
2. **Always use context managers for clients and async credentials.** Wrap every client in `with DataLakeServiceClient(...) as client:` (sync) or `async with DataLakeServiceClient(...) as client:` (async). For async `DefaultAzureCredential` from `azure.identity.aio`, also use `async with credential:` so tokens and transports are cleaned up.
3. **Use `DefaultAzureCredential`** for portable auth across local dev and Azure (avoid connection strings / API keys when possible).
4. **Use hierarchical namespace** for file system semantics
5. **Use `append_data` + `flush_data`** for large file uploads
6. **Set ACLs at directory level** and inherit to children
7. **Use async client** for high-throughput scenarios
8. **Use `get_paths` with `recursive=True`** for full directory listing
9. **Set metadata** for custom file attributes
10. **Consider Blob API** for simple object storage use cases

所有檔案

1 個檔案

安裝 azure-storage-file-datalake-py

將技能檔案下載並解壓至 .claude/skills/ 目錄。

下載 ZIP

複製儲存庫並將技能檔案複製到您的專案中。

git clone https://github.com/microsoft/skills/tree/main/.github/plugins/azure-sdk-python/skills/azure-storage-file-datalake-py # Copy SKILL.md to your .claude/skills/ directory

複製 複製
快速設定: 將技能資料夾複製到 .claude/skills/ 目錄。Claude 將自動檢測並使用該技能。
儲存庫 microsoft/skills

相關技能

base44-cli
更新時間 2026-06-29
klingai-upgrade-migration
更新時間 2026-07-03
Railway CLI Management
更新時間 2026-07-02
Verification &amp; Quality Assurance
更新時間 2026-06-29
OR