azure-storage-file-datalake-py
microsoft/skills
계층형 파일 시스템, 빅데이터 분석, 파일/디렉토리 작업을 위해 Python SDK로 Azure Data Lake Storage Gen2를 관리합니다.
...모든 것을 확장하십시오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>인증 및 수명 주기
🔑 아래 모든 코드 샘플에 적용되는 두 가지 규칙이 있습니다:
DefaultAzureCredential을 우선적으로 사용하십시오. 코드 변경 없이 로컬(Azure CLI / VS Code / Developer CLI) 및 Azure(관리된 ID, 워크로드 ID) 환경에서 작동합니다. 연결 문자열이나 계정/API 키는 사용하지 마십시오. 이러한 키는 Entra 감사 및 회전 기능을 우회합니다.
- 로컬 개발:
DefaultAzureCredential은 그대로 작동합니다.- 프로덕션:
AZURE_TOKEN_CREDENTIALS=prod(또는AZURE_TOKEN_CREDENTIALS=<specific_credential></specific_credential>)를 설정하여 자격 증명 체인을 프로덕션 안전 자격 증명으로 제한하십시오.- 모든 클라이언트를 컨텍스트 관리자로 감싸십시오. 이를 통해 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>모범 사례
- 동기 또는 비동기 중 하나를 선택하고 일관성을 유지하십시오. 동일한 호출 경로에서
azure.storage.filedatalake동기 클라이언트와azure.storage.filedatalake.aio비동기 클라이언트를 혼합하지 마십시오. 모듈당 하나의 모드를 선택하십시오. - 클라이언트 및 비동기 자격 증명에 항상 컨텍스트 관리자를 사용하십시오. 모든 클라이언트를
with DataLakeServiceClient(...) as client:(동기) 또는async with DataLakeServiceClient(...) as client:(비동기)로 감싸십시오.azure.identity.aio의 비동기DefaultAzureCredential의 경우 토큰과 전송을 정리하기 위해async with credential:도 사용하십시오. - 로컬 개발 및 Azure 전반에서 이식 가능한 인증을 위해
DefaultAzureCredential을 사용하십시오(가능한 경우 연결 문자열/API 키 사용 피함). - 파일 시스템 세맨틱스를 위해 계층형 네임스페이스 사용
- 대용량 파일 업로드를 위해
append_data+flush_data사용 - 디렉토리 수준에서 ACL 설정 및 하위 항목 상속
- 고처리량 시나리오에 비동기 클라이언트 사용
- 전체 디렉토리 나열을 위해
recursive=True와 함께get_paths사용 - 사용자 정의 파일 속성을 위해 메타데이터 설정
- 단순 객체 저장소 사용 사례의 경우 Blob API 고려
---
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
복사





집
