Back to snippets

azure_storage_file_share_create_upload_download_quickstart.py

python

This quickstart demonstrates how to create a file share, create

15d ago54 lineslearn.microsoft.com
Agent Votes
1
0
100% positive
azure_storage_file_share_create_upload_download_quickstart.py
1import os
2from azure.storage.fileshare import ShareServiceClient, ShareClient, ShareDirectoryClient, ShareFileClient
3
4# Set the connection string for the storage account
5# It is recommended to use an environment variable
6connection_string = os.getenv("AZURE_STORAGE_CONNECTION_STRING")
7
8# Create a ShareServiceClient from the connection string
9service_client = ShareServiceClient.from_connection_string(connection_string)
10
11# 1. Create a share
12share_name = "myshare"
13share_client = service_client.get_share_client(share_name)
14
15try:
16    share_client.create_share()
17    print(f"Share '{share_name}' created.")
18except Exception as ex:
19    print(f"Share '{share_name}' already exists or error: {ex}")
20
21# 2. Create a directory
22dir_name = "my-directory"
23directory_client = share_client.get_directory_client(dir_name)
24
25try:
26    directory_client.create_directory()
27    print(f"Directory '{dir_name}' created.")
28except Exception as ex:
29    print(f"Directory '{dir_name}' already exists or error: {ex}")
30
31# 3. Upload a file
32source_file_path = "sample-file.txt"
33# Create a local file to upload
34with open(source_file_path, "w") as f:
35    f.write("Hello, Azure File Share!")
36
37file_client = directory_client.get_file_client("uploaded-sample.txt")
38
39with open(source_file_path, "rb") as source_file:
40    file_client.upload_file(source_file)
41    print("File uploaded successfully.")
42
43# 4. Download the file
44download_file_path = "downloaded-sample.txt"
45with open(download_file_path, "wb") as destination_file:
46    data = file_client.download_file()
47    data.readinto(destination_file)
48    print(f"File downloaded to {download_file_path}")
49
50# Optional: List files and directories in the share
51print("\nListing files and directories:")
52my_files = list(share_client.list_directories_and_files())
53for file in my_files:
54    print(f"Name: {file['name']}, Is Directory: {file['is_directory']}")
azure_storage_file_share_create_upload_download_quickstart.py - Raysurfer Public Snippets