选项
首页首页 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 将自动检测并使用该技能。

相关技能

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