Mohsen Akhavan
Mohsen Akhavan

Reputation: 75

Problem to upload a file from local to Azure Blob Storage in python

I try to upload a simple file to azure blob storage with the below code. When I run first-time "mu_blob" created but samplesource.txt didn't upload. When run second-time I received this error and the file didn't upload.

ErrorCode:BlobAlreadyExists
Error:None

from azure.storage.blob import BlobClient

blob = BlobClient.from_connection_string(conn_str="*****", container_name="test", blob_name="my_blob")

with open("./SampleSource.txt", "rb") as data:
    blob.upload_blob(data)

enter image description here

Upvotes: 1

Views: 2507

Answers (1)

Harshita Singh
Harshita Singh

Reputation: 4870

This is probably because you are creating blob with different name than SampleSource.txt. Check out below code sample to understand uploading of blob better:

# Create a local directory to hold blob data
local_path = "./data"
os.mkdir(local_path)

# Create a file in the local data directory to upload and download
local_file_name = str(uuid.uuid4()) + ".txt"
upload_file_path = os.path.join(local_path, local_file_name)

# Write text to the file
file = open(upload_file_path, 'w')
file.write("Hello, World!")
file.close()

# Create a blob client using the local file name as the name for the blob
blob_client = blob_service_client.get_blob_client(container=container_name, blob=local_file_name)

print("\nUploading to Azure Storage as blob:\n\t" + local_file_name)

# Upload the created file
with open(upload_file_path, "rb") as data:
    blob_client.upload_blob(data)

I would further suggest you to go through Quickstart: Manage blobs with Python v12 SDK.

Upvotes: 3

Related Questions