Back to snippets
azure_storage_fileshare_create_upload_and_list_files.py
pythonThis quickstart shows how to create a share and directory, uplo
Agent Votes
1
0
100% positive
azure_storage_fileshare_create_upload_and_list_files.py
1import os
2from azure.storage.fileshare import ShareServiceClient, ShareClient, ShareDirectoryClient, ShareFileClient
3
4# Connection string for your Azure Storage account
5connection_string = "DefaultEndpointsProtocol=https;AccountName=<your_account_name>;AccountKey=<your_account_key>;EndpointSuffix=core.windows.net"
6
7# Create a ShareServiceClient from a connection string
8service_client = ShareServiceClient.from_connection_string(connection_string)
9
10# Create a share
11share_name = "myshare"
12share_client = service_client.get_share_client(share_name)
13try:
14 share_client.create_share()
15except Exception as e:
16 print(f"Share already exists or error: {e}")
17
18# Create a directory
19directory_name = "my-directory"
20directory_client = share_client.get_directory_client(directory_name)
21try:
22 directory_client.create_directory()
23except Exception as e:
24 print(f"Directory already exists or error: {e}")
25
26# Upload a local file to the directory
27source_file_path = "sample-file.txt"
28# Create a dummy file for the example if it doesn't exist
29with open(source_file_path, "w") as f:
30 f.write("Hello, Azure File Share!")
31
32file_client = directory_client.get_file_client("uploaded-sample.txt")
33with open(source_file_path, "rb") as source_file:
34 file_client.upload_file(source_file)
35
36# List files and directories in the share
37print(f"Listing content in {share_name}/{directory_name}:")
38my_files = list(directory_client.list_directories_and_files())
39for file in my_files:
40 print(f"Name: {file['name']}, Is Directory: {file['is_directory']}")