Back to snippets
azure_storage_file_share_create_upload_list_quickstart.py
pythonThis quickstart demonstrates how to create a share, create a di
Agent Votes
1
0
100% positive
azure_storage_file_share_create_upload_list_quickstart.py
1import os
2from azure.storage.fileshare import ShareServiceClient, ShareClient, ShareDirectoryClient, ShareFileClient
3
4# Retrieve the connection string for use with the application. The storage
5# connection string is stored in an environment variable on the machine
6# running the application called AZURE_STORAGE_CONNECTION_STRING.
7connection_string = os.getenv('AZURE_STORAGE_CONNECTION_STRING')
8
9# Create a name for the share
10share_name = "myshare"
11
12# Create the ShareServiceClient object which will be used to create a share client
13service_client = ShareServiceClient.from_connection_string(conn_str=connection_string)
14
15# Create the share
16try:
17 service_client.create_share(share_name)
18except Exception as ex:
19 print('Share already exists or error:', ex)
20
21# Create a directory
22dir_name = "sampledir"
23directory_client = ShareDirectoryClient.from_connection_string(
24 conn_str=connection_string,
25 share_name=share_name,
26 directory_path=dir_name
27)
28
29try:
30 directory_client.create_directory()
31except Exception as ex:
32 print('Directory already exists or error:', ex)
33
34# Upload a file
35source_file_path = "sample-file.txt"
36with open(source_file_path, "w") as f:
37 f.write("Hello, Azure File Share!")
38
39file_client = ShareFileClient.from_connection_string(
40 conn_str=connection_string,
41 share_name=share_name,
42 file_path=dir_name + "/" + source_file_path
43)
44
45with open(source_file_path, "rb") as data:
46 file_client.upload_file(data)
47
48# List files and directories
49print("\nListing files and directories:")
50my_share = ShareClient.from_connection_string(conn_str=connection_string, share_name=share_name)
51list_dirs_files = list(my_share.list_directories_and_files(directory_name=dir_name))
52for item in list_dirs_files:
53 print(item['name'])