You're asking about Azure Files (often referred to as Azure Shared File Storage), which is different from Azure Blob Storage. While both are part of Azure Storage, they serve different purposes and use different SDKs and concepts.
Azure Files provides fully managed file shares in the cloud that are accessible via the industry-standard Server Message Block (SMB) protocol or Network File System (NFS) protocol, or via the Azure Files REST API.
Here's how to download an image file from Azure File Share and save it to a specific local directory using Python.
Prerequisites
Azure Storage Account: An active Azure subscription and a storage account created.
File Share: A file share created within your storage account.
Directory (Optional): If your image is within a subdirectory inside the file share, note that path.
Image File: At least one image file (e.g., my_image.jpg) uploaded to that file share (and optionally, its subdirectory).
Python Installed: Python 3.7+ is recommended.
Azure Storage File Share SDK: Install the necessary Python package:
(azure-identity is for more secure authentication methods like Azure AD.)
Method 1: Using Connection String (Recommended for Quick Start/Development)
This is the simplest method for quick testing or development environments. However, it's less secure for production applications as it hardcodes credentials.
1. Get your Storage Account Connection String:
Go to your Azure Storage Account in the Azure Portal.
Navigate to Access keys under Security + networking.
Copy one of the Connection string values. It will look something like:
DefaultEndpointsProtocol=https;AccountName=yourstorageaccountname;AccountKey=YOUR_ACCOUNT_KEY_HERE;EndpointSuffix=core.windows.net
2. Python Code:
python
import os
from azure.storage.file_share import ShareServiceClient
from azure.core.exceptions import ResourceNotFoundError
# --- Configuration ---
# 1. Replace with your actual connection string
# Find this in Azure Portal -> Storage Account -> Access keys
CONNECTION_STRING = "DefaultEndpointsProtocol=https;AccountName=yourstorageaccountname;AccountKey=YOUR_ACCOUNT_KEY_HERE;EndpointSuffix=core.windows.net"
# 2. Replace with the name of your file share
SHARE_NAME = "your-file-share-name"
# 3. Replace with the path to the directory within the share where your file resides.
# Use an empty string "" if the file is directly in the root of the share.
DIRECTORY_NAME = "images" # e.g., "photos/vacation" or "" for root
# 4. Replace with the exact name of the image file in your file share
FILE_NAME = "my_image.jpg"
# 5. The local directory where you want to save the image
LOCAL_DOWNLOAD_DIRECTORY = "downloaded_files"
# 6. The desired filename for the downloaded image
LOCAL_FILENAME = "downloaded_my_image.jpg"
# Or, to keep the original name: LOCAL_FILENAME = FILE_NAME
# --- End Configuration ---
def download_file_from_share_connection_string(connection_string, share_name, directory_name, file_name, local_directory, local_filename):
"""
Downloads a file from Azure File Share to a local file using a connection string.
"""
local_file_path = os.path.join(local_directory, local_filename)
try:
# Create the ShareServiceClient object
service_client = ShareServiceClient.from_connection_string(connection_string)
# Get a client for the specific share
share_client = service_client.get_share_client(share_name)
# Construct the full path of the file within the share
# This correctly handles cases where directory_name is empty (root of share)
full_file_path_in_share = os.path.join(directory_name, file_name) if directory_name else file_name
# Get a client for the specific file
file_client = share_client.get_file_client(full_file_path_in_share)
print(f"Attempting to download '{full_file_path_in_share}' from share '{share_name}'...")
# Ensure the local directory exists
os.makedirs(local_directory, exist_ok=True)
# Download the file data
with open(local_file_path, "wb") as download_file:
download_file.write(file_client.download_file().readall()) # .readall() reads entire file
print(f"Successfully downloaded '{file_name}' to '{local_file_path}'")
except ResourceNotFoundError:
print(f"Error: File '{full_file_path_in_share}' not found in share '{share_name}'.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
download_file_from_share_connection_string(
CONNECTION_STRING,
SHARE_NAME,
DIRECTORY_NAME,
FILE_NAME,
LOCAL_DOWNLOAD_DIRECTORY,
LOCAL_FILENAME
)
Method 2: Using Azure AD / DefaultAzureCredential (Recommended for Production)
This is the most secure and recommended method for production applications. It avoids hardcoding credentials and uses Azure Identity to authenticate, often leveraging Managed Identities for Azure resources or environment variables for local development.
1. Setup Azure AD Authentication (Choose One):
Managed Identity (Azure Resources): If your Python application is running on an Azure VM, App Service, Function App, etc., enable a System-Assigned Managed Identity for that resource. Then, grant this Managed Identity the "Storage File Data Reader" role on your storage account or share. No code changes for credentials needed!
Environment Variables (Local Development): Set environment variables like AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET (for a service principal) or AZURE_USERNAME, AZURE_PASSWORD (for interactive login).
Azure CLI Login: If you're logged into Azure CLI (az login), DefaultAzureCredential can often pick up those credentials automatically.
2. Grant Permissions:
Go to your Azure Storage Account in the Azure Portal.
Navigate to Access control (IAM).
Click + Add -> Add role assignment.
Search for and select the role "Storage File Data Reader".
Assign it to your Managed Identity, Service Principal, or User account that will be running the code.
3. Python Code:
python
import os
from azure.storage.file_share import ShareServiceClient
from azure.identity import DefaultAzureCredential
from azure.core.exceptions import ResourceNotFoundError
# --- Configuration ---
# 1. Your Storage Account Name (not the full URL)
ACCOUNT_NAME = "yourstorageaccountname"
# 2. Replace with the name of your file share
SHARE_NAME = "your-file-share-name"
# 3. Replace with the path to the directory within the share where your file resides.
# Use an empty string "" if the file is directly in the root of the share.
DIRECTORY_NAME = "images" # e.g., "photos/vacation" or "" for root
# 4. Replace with the exact name of the image file in your file share
FILE_NAME = "my_image.jpg"
# 5. The local directory where you want to save the image
LOCAL_DOWNLOAD_DIRECTORY = "downloaded_files"
# 6. The desired filename for the downloaded image
LOCAL_FILENAME = "downloaded_my_image.jpg"
# Or, to keep the original name: LOCAL_FILENAME = FILE_NAME
# --- End Configuration ---
def download_file_from_share_aad(account_name, share_name, directory_name, file_name, local_directory, local_filename):
"""
Downloads a file from Azure File Share using Azure AD authentication.
"""
local_file_path = os.path.join(local_directory, local_filename)
# Note the '.file.core.windows.net' suffix for Azure Files
file_service_url = f"https://{account_name}.file.core.windows.net"
try:
# Create DefaultAzureCredential
credential = DefaultAzureCredential()
# Create the ShareServiceClient object with the credential
service_client = ShareServiceClient(account_url=file_service_url, credential=credential)
# Get a client for the specific share
share_client = service_client.get_share_client(share_name)
# Construct the full path of the file within the share
full_file_path_in_share = os.path.join(directory_name, file_name) if directory_name else file_name
# Get a client for the specific file
file_client = share_client.get_file_client(full_file_path_in_share)
print(f"Attempting to download '{full_file_path_in_share}' from share '{share_name}' using AAD...")
# Ensure the local directory exists
os.makedirs(local_directory, exist_ok=True)
# Download the file data
with open(local_file_path, "wb") as download_file:
download_file.write(file_client.download_file().readall())
print(f"Successfully downloaded '{file_name}' to '{local_file_path}'")
except ResourceNotFoundError:
print(f"Error: File '{full_file_path_in_share}' not found in share '{share_name}'.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
download_file_from_share_aad(
ACCOUNT_NAME,
SHARE_NAME,
DIRECTORY_NAME,
FILE_NAME,
LOCAL_DOWNLOAD_DIRECTORY,
LOCAL_FILENAME
)
Method 3: Using Shared Access Signature (SAS) Token
A SAS token provides delegated access to resources in your storage account. It allows you to grant clients access to data in your storage account without sharing your account keys. It's good for temporary, limited access.
1. Generate a SAS Token:
Go to your Azure Storage Account in the Azure Portal.
Navigate to Shared access signature under Security + networking.
Select the allowed services (File), resource types (Service, Container, Object) - for file share operations, "Service" and "Container" (for share-level) or "Object" (for file-level) are usually needed.
Select permissions (Read for download).
Set a start and expiry date.
Click Generate SAS and connection string.
Copy the SAS token (the part starting with ?sv=...).
2. Python Code:
python
import os
from azure.storage.file_share import ShareServiceClient
from azure.core.exceptions import ResourceNotFoundError
# --- Configuration ---
# 1. Your Storage Account Name
ACCOUNT_NAME = "yourstorageaccountname"
# 2. Your SAS Token (starting with ?)
# Find this in Azure Portal -> Storage Account -> Shared access signature
SAS_TOKEN = "?sv=2022-11-02&ss=f&srt=sco&sp=rl&se=2023-12-31T23:59:59Z&st=2023-01-01T00:00:00Z&spr=https&sig=YOUR_SAS_SIGNATURE_HERE"
# 3. Replace with the name of your file share
SHARE_NAME = "your-file-share-name"
# 4. Replace with the path to the directory within the share where your file resides.
# Use an empty string "" if the file is directly in the root of the share.
DIRECTORY_NAME = "images" # e.g., "photos/vacation" or "" for root
# 5. Replace with the exact name of the image file in your file share
FILE_NAME = "my_image.jpg"
# 6. The local directory where you want to save the image
LOCAL_DOWNLOAD_DIRECTORY = "downloaded_files"
# 7. The desired filename for the downloaded image
LOCAL_FILENAME = "downloaded_my_image.jpg"
# Or, to keep the original name: LOCAL_FILENAME = FILE_NAME
# --- End Configuration ---
def download_file_from_share_sas(account_name, sas_token, share_name, directory_name, file_name, local_directory, local_filename):
"""
Downloads a file from Azure File Share using a SAS token.
"""
local_file_path = os.path.join(local_directory, local_filename)
file_service_url = f"https://{account_name}.file.core.windows.net"
try:
# Create the ShareServiceClient object with the SAS token
service_client = ShareServiceClient(account_url=file_service_url, credential=sas_token)
# Get a client for the specific share
share_client = service_client.get_share_client(share_name)
# Construct the full path of the file within the share
full_file_path_in_share = os.path.join(directory_name, file_name) if directory_name else file_name
# Get a client for the specific file
file_client = share_client.get_file_client(full_file_path_in_share)
print(f"Attempting to download '{full_file_path_in_share}' from share '{share_name}' using SAS...")
# Ensure the local directory exists
os.makedirs(local_directory, exist_ok=True)
# Download the file data
with open(local_file_path, "wb") as download_file:
download_file.write(file_client.download_file().readall())
print(f"Successfully downloaded '{file_name}' to '{local_file_path}'")
except ResourceNotFoundError:
print(f"Error: File '{full_file_path_in_share}' not found in share '{share_name}'.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
download_file_from_share_sas(
ACCOUNT_NAME,
SAS_TOKEN,
SHARE_NAME,
DIRECTORY_NAME,
FILE_NAME,
LOCAL_DOWNLOAD_DIRECTORY,
LOCAL_FILENAME
)
Key Considerations and Best Practices:
Security:
NEVER hardcode sensitive credentials (connection strings, account keys) in production code. Use environment variables, Azure Key Vault, or Managed Identities.
SAS tokens offer better security than connection strings for delegated access but should still be managed carefully (short expiry, minimum required permissions).
Directory Structure: Azure Files supports a true hierarchical directory structure, unlike Azure Blobs' flat namespace. Make sure DIRECTORY_NAME accurately reflects the path within the share.
Error Handling: The provided examples include basic try-except blocks. For production, implement more robust error handling (e.g., retries for transient errors, specific exception handling for different Azure errors).
Directory Management:os.makedirs(local_directory, exist_ok=True) is crucial to ensure the target directory exists before attempting to write the file.
File Overwriting: The with open(local_file_path, "wb") statement will overwrite the file if it already exists. If you want to prevent overwriting, you'll need to add a check (e.g., if os.path.exists(local_file_path): ...).
Large Files: For very large files, file_client.download_file().readall() loads the entire file into memory. For extremely large files, consider downloading in chunks.
User
Besides the downloading function, I want to know how to list files in a directory and upload local file to Azure share file storage
Assistant
You're looking to expand your Azure File Storage interactions beyond just downloading! This is a common and useful set of operations.
Here's how to list files in a directory within an Azure File Share and upload a local file to it, using Python. We'll again use the azure-storage-file-share SDK.
Prerequisites
All prerequisites from the previous answer for Azure File Storage apply:
For Listing: You need at least "Storage File Data Reader" role on the storage account or file share.
For Uploading: You need at least "Storage File Data Contributor" role on the storage account or file share.
Shared Configuration and Client Initialization
To keep the examples clean and avoid repetition, we'll use a common way to initialize the ShareServiceClient. I'll focus on Azure AD / DefaultAzureCredential (recommended for production) and Connection String (recommended for quick development).
import os
from azure.storage.file_share import ShareServiceClient, ShareDirectoryClient
from azure.identity import DefaultAzureCredential
from azure.core.exceptions import ResourceNotFoundError, ResourceExistsError
# --- COMMON CONFIGURATION ---
# Replace with your actual values
ACCOUNT_NAME = "yourstorageaccountname"
SHARE_NAME = "your-file-share-name"
# Options for authentication:
# 1. Connection String (Development/Quick Start)
# CONNECTION_STRING = "DefaultEndpointsProtocol=https;AccountName=yourstorageaccountname;AccountKey=YOUR_ACCOUNT_KEY_HERE;EndpointSuffix=core.windows.net"
# 2. SAS Token (Temporary/Limited Access)
# SAS_TOKEN = "?sv=2022-11-02&ss=f&srt=sco&sp=rwdl&se=2023-12-31T23:59:59Z&st=2023-01-01T00:00:00Z&spr=https&sig=YOUR_SAS_SIGNATURE_HERE"
# (Note: For upload, SAS needs 'w' write permission)
# --- END COMMON CONFIGURATION ---
def get_share_service_client(account_name, connection_string=None, sas_token=None):
"""
Initializes and returns a ShareServiceClient based on the provided authentication method.
Prioritizes connection string, then SAS, then DefaultAzureCredential.
"""
file_service_url = f"https://{account_name}.file.core.windows.net"
if connection_string:
print("Using Connection String for authentication.")
return ShareServiceClient.from_connection_string(connection_string)
elif sas_token:
print("Using SAS Token for authentication.")
return ShareServiceClient(account_url=file_service_url, credential=sas_token)
else:
print("Using DefaultAzureCredential for authentication.")
# DefaultAzureCredential will try environment variables, managed identity, Azure CLI, etc.
credential = DefaultAzureCredential()
return ShareServiceClient(account_url=file_service_url, credential=credential)
# Example usage (choose one for your main execution):
# service_client = get_share_service_client(ACCOUNT_NAME, connection_string=CONNECTION_STRING)
service_client = get_share_service_client(ACCOUNT_NAME) # For AAD/DefaultAzureCredential
# service_client = get_share_service_client(ACCOUNT_NAME, sas_token=SAS_TOKEN) # For SAS Token
1. Listing Files in a Directory
This function will traverse a specified directory within your Azure File Share and print out its contents (files and subdirectories).
python
def list_files_in_share_directory(service_client: ShareServiceClient, share_name: str, directory_path: str = ""):
"""
Lists files and subdirectories in a specified path within an Azure File Share.
Args:
service_client: An initialized ShareServiceClient.
share_name: The name of the file share.
directory_path: The path to the directory within the share (e.g., "my_folder/subfolder").
Use "" for the root directory of the share.
"""
print(f"\n--- Listing contents of '{directory_path if directory_path else 'root'}' in share '{share_name}' ---")
try:
share_client = service_client.get_share_client(share_name)
if directory_path:
directory_client = share_client.get_directory_client(directory_path)
# Verify directory exists before listing
directory_properties = directory_client.get_directory_properties()
print(f"Directory '{directory_path}' properties: {directory_properties['name']}, Etag: {directory_properties['etag']}")
else:
# If directory_path is empty, we are listing the root, so use the share_client directly
directory_client = share_client
# List contents
items = directory_client.list_directories_and_files()
found_items = False
for item in items:
found_items = True
if item.is_directory:
print(f" [DIR] {item.name}")
else:
print(f" [FILE] {item.name} ({item.size / 1024:.2f} KB)") # Size in KB
if not found_items:
print(" (Directory is empty or no items found)")
except ResourceNotFoundError:
print(f"Error: Share '{share_name}' or directory '{directory_path}' not found.")
except Exception as e:
print(f"An unexpected error occurred during listing: {e}")
# Example usage for listing:
# list_files_in_share_directory(service_client, SHARE_NAME, "images")
# list_files_in_share_directory(service_client, SHARE_NAME, "") # List root directory
2. Uploading a Local File to Azure File Share
This function will take a local file and upload it to a specified directory within your Azure File Share. It includes a helper to ensure the target directory exists, as Azure Files requires parent directories to exist before you can upload a file into them.
python
def ensure_directory_exists_in_share(share_client, directory_path: str):
"""
Ensures that a specified directory path exists within the Azure File Share.
It will create parent directories recursively if they don't exist.
"""
if not directory_path:
return # No directory to create if target is root
current_path = []
# Split the directory path into segments and create them one by one
for segment in directory_path.split('/'): # Use '/' as path separator for Azure Files
if not segment: # Handle cases like "folder1//folder2" or trailing slash
continue
current_path.append(segment)
dir_to_create = "/".join(current_path)
directory_client = share_client.get_directory_client(dir_to_create)
try:
print(f" Attempting to create directory: {dir_to_create}")
directory_client.create_directory()
print(f" Successfully created directory: {dir_to_create}")
except ResourceExistsError:
print(f" Directory already exists: {dir_to_create}")
except Exception as e:
print(f" Error creating directory '{dir_to_create}': {e}")
raise # Re-raise if it's not a 'ResourceExistsError'
def upload_local_file_to_share(service_client: ShareServiceClient, share_name: str, local_file_path: str, remote_directory_path: str = "", remote_file_name: str = None):
"""
Uploads a local file to a specified directory in an Azure File Share.
Args:
service_client: An initialized ShareServiceClient.
share_name: The name of the file share.
local_file_path: The full path to the local file to upload.
remote_directory_path: The target directory path within the share (e.g., "uploads/data").
Use "" for the root directory of the share.
remote_file_name: The desired name for the file in the share. If None, uses local file's name.
"""
if not os.path.exists(local_file_path):
print(f"Error: Local file not found at '{local_file_path}'. Aborting upload.")
return
# Determine the remote file name
if remote_file_name is None:
remote_file_name = os.path.basename(local_file_path)
# Construct the full remote path
full_remote_file_path = os.path.join(remote_directory_path, remote_file_name).replace(os.sep, '/') # Ensure '/' as separator
print(f"\n--- Uploading '{local_file_path}' to '{full_remote_file_path}' in share '{share_name}' ---")
try:
share_client = service_client.get_share_client(share_name)
# Ensure the target directory exists (and its parents)
ensure_directory_exists_in_share(share_client, remote_directory_path)
# Get the file client for the target file
file_client = share_client.get_file_client(full_remote_file_path)
# Open the local file and upload
with open(local_file_path, "rb") as data:
print(f"Uploading file '{local_file_path}'...")
file_client.upload_file(data)
print(f"Successfully uploaded '{local_file_path}' to '{full_remote_file_path}'")
except ResourceNotFoundError:
print(f"Error: Share '{share_name}' not found.")
except Exception as e:
print(f"An unexpected error occurred during upload: {e}")
# Example usage for uploading:
# 1. Create a dummy file for testing
dummy_file_path = "test_upload_image.jpg"
with open(dummy_file_path, "wb") as f:
f.write(b"\x00" * 1024) # A 1KB dummy file
# upload_local_file_to_share(service_client, SHARE_NAME, dummy_file_path, "uploaded_images", "my_uploaded_photo.jpg")
# upload_local_file_to_share(service_client, SHARE_NAME, dummy_file_path, "") # Upload to root
Putting It All Together (Example Script)
python
import os
from azure.storage.file_share import ShareServiceClient, ShareDirectoryClient
from azure.identity import DefaultAzureCredential
from azure.core.exceptions import ResourceNotFoundError, ResourceExistsError
# --- COMMON CONFIGURATION ---
# Replace with your actual values
ACCOUNT_NAME = "yourstorageaccountname"
SHARE_NAME = "your-file-share-name"
# >>> Choose one authentication method for execution <<<
# Method 1: Connection String (Uncomment and replace)
# CONNECTION_STRING = "DefaultEndpointsProtocol=https;AccountName=yourstorageaccountname;AccountKey=YOUR_ACCOUNT_KEY_HERE;EndpointSuffix=core.windows.net"
# service_client_auth_param = {"connection_string": CONNECTION_STRING}
# Method 2: Azure AD / DefaultAzureCredential (Recommended for Production)
service_client_auth_param = {} # DefaultAzureCredential is used if no other param is provided
# Method 3: SAS Token (Uncomment and replace)
# SAS_TOKEN = "?sv=2022-11-02&ss=f&srt=sco&sp=rwdl&se=2023-12-31T23:59:59Z&st=2023-01-01T00:00:00Z&spr=https&sig=YOUR_SAS_SIGNATURE_HERE"
# service_client_auth_param = {"sas_token": SAS_TOKEN}
# --- END COMMON CONFIGURATION ---
def get_share_service_client(account_name: str, **kwargs) -> ShareServiceClient:
"""
Initializes and returns a ShareServiceClient based on the provided authentication method.
"""
file_service_url = f"https://{account_name}.file.core.windows.net"
if "connection_string" in kwargs:
print("Using Connection String for authentication.")
return ShareServiceClient.from_connection_string(kwargs["connection_string"])
elif "sas_token" in kwargs:
print("Using SAS Token for authentication.")
return ShareServiceClient(account_url=file_service_url, credential=kwargs["sas_token"])
else:
print("Using DefaultAzureCredential for authentication.")
credential = DefaultAzureCredential()
return ShareServiceClient(account_url=file_service_url, credential=credential)
def list_files_in_share_directory(service_client: ShareServiceClient, share_name: str, directory_path: str = ""):
"""
Lists files and subdirectories in a specified path within an Azure File Share.
"""
print(f"\n--- Listing contents of '{directory_path if directory_path else 'root'}' in share '{share_name}' ---")
try:
share_client = service_client.get_share_client(share_name)
# For root directory, get_directory_client('') or share_client.get_directory_client() works
# If directory_path is not empty, get a specific directory client
directory_client = share_client.get_directory_client(directory_path)
# Check if the directory exists before listing
if directory_path: # Only check if not listing root
try:
directory_client.get_directory_properties()
print(f"Directory '{directory_path}' exists.")
except ResourceNotFoundError:
print(f"Directory '{directory_path}' does not exist.")
return
# List contents
items = directory_client.list_directories_and_files()
found_items = False
for item in items:
found_items = True
if item.is_directory:
print(f" [DIR] {item.name}")
else:
print(f" [FILE] {item.name} ({item.size / 1024:.2f} KB)") # Size in KB
if not found_items:
print(" (Directory is empty or no items found)")
except ResourceNotFoundError:
print(f"Error: Share '{share_name}' not found.")
except Exception as e:
print(f"An unexpected error occurred during listing: {e}")
def ensure_directory_exists_in_share(share_client, directory_path: str):
"""
Ensures that a specified directory path exists within the Azure File Share.
It will create parent directories recursively if they don't exist.
"""
if not directory_path:
return # No directory to create if target is root
current_path_segments = []
for segment in directory_path.split('/'): # Use '/' as path separator for Azure Files
if not segment:
continue
current_path_segments.append(segment)
dir_to_create = "/".join(current_path_segments)
directory_client = share_client.get_directory_client(dir_to_create)
try:
print(f" Attempting to create directory: {dir_to_create}")
directory_client.create_directory()
print(f" Successfully created directory: {dir_to_create}")
except ResourceExistsError:
print(f" Directory already exists: {dir_to_create}")
except Exception as e:
print(f" Error creating directory '{dir_to_create}': {e}")
raise # Re-raise if it's not a 'ResourceExistsError'
def upload_local_file_to_share(service_client: ShareServiceClient, share_name: str, local_file_path: str, remote_directory_path: str = "", remote_file_name: str = None):
"""
Uploads a local file to a specified directory in an Azure File Share.
"""
if not os.path.exists(local_file_path):
print(f"Error: Local file not found at '{local_file_path}'. Aborting upload.")
return
if not os.path.isfile(local_file_path):
print(f"Error: Provided local path '{local_file_path}' is not a file. Aborting upload.")
return
# Determine the remote file name
if remote_file_name is None:
remote_file_name = os.path.basename(local_file_path)
# Construct the full remote path. Azure Files uses '/' as path separator.
full_remote_file_path = os.path.join(remote_directory_path, remote_file_name).replace(os.sep, '/')
print(f"\n--- Uploading '{local_file_path}' to '{full_remote_file_path}' in share '{share_name}' ---")
try:
share_client = service_client.get_share_client(share_name)
# Ensure the target directory exists (and its parents)
ensure_directory_exists_in_share(share_client, remote_directory_path)
# Get the file client for the target file
file_client = share_client.get_file_client(full_remote_file_path)
# Open the local file and upload
print(f"Uploading file '{local_file_path}'...")
with open(local_file_path, "rb") as data:
file_client.upload_file(data)
print(f"Successfully uploaded '{local_file_path}' to '{full_remote_file_path}'")
except ResourceNotFoundError:
print(f"Error: Share '{share_name}' not found.")
except Exception as e:
print(f"An unexpected error occurred during upload: {e}")
if __name__ == "__main__":
# Initialize the service client using your chosen authentication method
service_client = get_share_service_client(ACCOUNT_NAME, **service_client_auth_param)
# --- DEMONSTRATION ---
# 1. Create a dummy file for testing upload
dummy_file_path = "local_test_image.jpg"
with open(dummy_file_path, "wb") as f:
f.write(b"This is a dummy image file content." * 10) # 300 bytes
# 2. Upload the dummy file
upload_target_directory = "my_uploaded_files/photos" # Will create these directories if they don't exist
upload_local_file_to_share(service_client, SHARE_NAME, dummy_file_path, upload_target_directory, "uploaded_photo.jpg")
# upload_local_file_to_share(service_client, SHARE_NAME, dummy_file_path, "") # Example: Upload to root
# 3. List files in the target directory after upload
list_files_in_share_directory(service_client, SHARE_NAME, upload_target_directory)
# 4. List files in the root directory
list_files_in_share_directory(service_client, SHARE_NAME, "")
# Clean up the dummy file
if os.path.exists(dummy_file_path):
os.remove(dummy_file_path)
print(f"\nCleaned up local dummy file: {dummy_file_path}")
How to Run:
Save the code: Save the combined code above as a Python file (e.g., azure_file_ops.py).
Configure:
Replace yourstorageaccountname and your-file-share-name with your actual Azure details.
Crucially, uncomment and configure ONE of the service_client_auth_param sections based on whether you're using Connection String, SAS Token, or DefaultAzureCredential.
Run from terminal:
bash
python azure_file_ops.py
This script will demonstrate how to upload a test file, then list the contents of the target directory and the share's root directory, giving you a complete picture of these common Azure File Share operations.