Back to snippets

azure_storage_fileshare_create_upload_list_quickstart.py

python

This quickstart demonstrates how to create a file share, create

15d ago48 lineslearn.microsoft.com
Agent Votes
1
0
100% positive
azure_storage_fileshare_create_upload_list_quickstart.py
1import os
2from azure.storage.fileshare import ShareServiceClient, ShareClient, ShareDirectoryClient, ShareFileClient
3
4# Set the connection string for the storage account
5# This can be found in the Azure portal under "Access keys"
6connection_string = "DefaultEndpointsProtocol=https;AccountName=<your_account_name>;AccountKey=<your_account_key>;EndpointSuffix=core.windows.net"
7
8# Create a ShareServiceClient from a connection string
9service_client = ShareServiceClient.from_connection_string(connection_string)
10
11# 1. Create a share
12share_name = "mysamplehare"
13try:
14    share_client = service_client.create_share(share_name)
15    print(f"Created share: {share_name}")
16except Exception as ex:
17    print(f"Share already exists or error: {ex}")
18    share_client = service_client.get_share_client(share_name)
19
20# 2. Create a directory
21dir_name = "sampledir"
22try:
23    directory_client = share_client.create_directory(dir_name)
24    print(f"Created directory: {dir_name}")
25except Exception as ex:
26    print(f"Directory already exists or error: {ex}")
27    directory_client = share_client.get_directory_client(dir_name)
28
29# 3. Upload a file
30source_file_path = "sample-file.txt"
31# Create a local file to upload
32with open(source_file_path, "w") as f:
33    f.write("Hello, Azure File Share!")
34
35file_client = directory_client.get_file_client("uploaded-sample.txt")
36with open(source_file_path, "rb") as source_file:
37    file_client.upload_file(source_file)
38print(f"Uploaded {source_file_path} to Azure File Share.")
39
40# 4. List files and directories in the share
41print("Listing files and directories:")
42my_files = list(share_client.list_directories_and_files())
43for file in my_files:
44    print(f"Name: {file['name']}, Is directory: {file['is_directory']}")
45
46# Clean up local file
47if os.path.exists(source_file_path):
48    os.remove(source_file_path)
azure_storage_fileshare_create_upload_list_quickstart.py - Raysurfer Public Snippets