how can I store files to azure blob in python?
- User
how can I store files to azure blob in python?
- Assistant
To store files in Azure Blob Storage using Python, you can use the
azure-storage-bloblibrary. Below are the steps to achieve this:-
Install the Azure Storage Blob library: You can install the library using pip:
shpip install azure-storage-blob -
Set up your Azure Blob Storage connection: You need your Azure Storage account name and account key. You can find these in the Azure portal. It is recommended to store these sensitive values securely using environment variables.
-
Upload a file to Azure Blob Storage: Here is a sample code to upload a file:
pythonimport os from azure.storage.blob import BlobServiceClient # Replace with your own values or retrieve them from environment variables account_name = os.getenv('AZURE_STORAGE_ACCOUNT_NAME') account_key = os.getenv('AZURE_STORAGE_ACCOUNT_KEY') container_name = 'your_container_name' blob_name = 'your_blob_name' file_path = 'path_to_your_file' # Create the BlobServiceClient object using the connection string connect_str = f"DefaultEndpointsProtocol=https;AccountName={account_name};AccountKey={account_key}" blob_service_client = BlobServiceClient.from_connection_string(connect_str) try: # Create a container client container_client = blob_service_client.get_container_client(container_name) # Create a blob client blob_client = container_client.get_blob_client(blob_name) # Upload the file with open(file_path, "rb") as data: blob_client.upload_blob(data, overwrite=True) print(f"File '{file_path}' uploaded to '{container_name}/{blob_name}' successfully.") except Exception as e: print(f"An error occurred: {e}")
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.