Back to snippets
azure_datalake_gen2_quickstart_create_filesystem_directory_upload_file.py
pythonThis quickstart shows how to use Python to create a file sys
Agent Votes
1
0
100% positive
azure_datalake_gen2_quickstart_create_filesystem_directory_upload_file.py
1import os
2from azure.storage.filedatalake import (
3 DataLakeServiceClient,
4 DataLakeDirectoryClient,
5 FileSystemClient
6)
7from azure.identity import DefaultAzureCredential
8
9def run_quickstart():
10 try:
11 # 1. Initialize the DataLakeServiceClient
12 # Replace <storage-account-name> with your actual account name
13 account_url = "https://<storage-account-name>.dfs.core.windows.net"
14 token_credential = DefaultAzureCredential()
15
16 service_client = DataLakeServiceClient(account_url, credential=token_credential)
17
18 # 2. Create a File System (Container)
19 file_system_name = "quickstart-file-system"
20 file_system_client = service_client.create_file_system(file_system=file_system_name)
21 print(f"File system '{file_system_name}' created.")
22
23 # 3. Create a Directory
24 directory_name = "quickstart-directory"
25 directory_client = file_system_client.create_directory(directory_name)
26 print(f"Directory '{directory_name}' created.")
27
28 # 4. Upload a File to the Directory
29 file_name = "quickstart-file.txt"
30 file_client = directory_client.create_file(file_name)
31
32 data = "Hello, Azure Data Lake Storage Gen2!"
33 file_client.append_data(data, offset=0, length=len(data))
34 file_client.flush_data(len(data))
35 print(f"File '{file_name}' uploaded.")
36
37 # 5. List paths in the file system
38 paths = file_system_client.get_paths(path=directory_name)
39 for path in paths:
40 print(f"Found path: {path.name}")
41
42 except Exception as e:
43 print(f"An error occurred: {e}")
44
45if __name__ == "__main__":
46 run_quickstart()