オプション
家 Skill DevOps と 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年9月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>

認証とライフサイクル

🔑 以下のすべてのコードサンプルに適用される2つのルールがあります:

  1. DefaultAzureCredential を優先してください。 これにより、ローカル環境(Azure CLI / VS Code / Developer CLI)および Azure(マネージド ID、ワークロード ID)で、コードの変更なしに動作します。接続文字列やアカウント/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"サイズ: {properties.size}")
print(f"最終更新日時: {properties.last_modified}")

# メタデータの設定
file_client.set_metadata(metadata={"processed": "true"})

アクセス制御(ACL)

# ACL の取得
acl = directory_client.get_access_control()
print(f"所有者: {acl['owner']}")
print(f"権限: {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 の非同期クライアントを混在させないでください。モジュールごとに1つのモードを選択してください。
  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_pathsrecursive=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年6月29日
klingai-upgrade-migration
更新された時間 2026年7月3日
Railway CLI Management
更新された時間 2026年7月2日
Verification &amp; Quality Assurance
更新された時間 2026年6月29日
OR