skip to Main Content

I am using the below code to append data to Azure blob using python.

from azure.storage.blob import AppendBlobService
append_blob_service = AppendBlobService(account_name='myaccount', account_key='mykey')

# The same containers can hold all types of blobs
append_blob_service.create_container('mycontainer')

# Append blobs must be created before they are appended to
append_blob_service.create_blob('mycontainer', 'myappendblob')
append_blob_service.append_blob_from_text('mycontainer', 'myappendblob', u'Hello, world!')

append_blob = append_blob_service.get_blob_to_text('mycontainer', 'myappendblob')

The above code works fine, but when I tried to insert new data, the old data gets overwritten.
Is there any way I can append data to ‘myappendblob’

2

Answers


  1. Try this code which is taken from the Document and it is given by @Harsh Jain ,

    from azure.storage.blob import AppendBlobService
       def append_data_to_blob(data):
         service = AppendBlobService(account_name="<Storage acc name>",
    
           account_key="<Storage acc key>")
    
         try:
    
           service.append_blob_from_text(container_name="<name of Conatiner >", blob_name="<The name of file>", text = data)
    
         except:
    
           service.create_blob(container_name="<name of Conatiner >", blob_name="<the name of file>")
    
           service.append_blob_from_text(container_name="<name of Conatiner>", blob_name="<the name of file>", text = data)
    
         print('Data got Appended ')
    
     append_data_to_blob('Hi blob')
    

    Taken References from:

    https://www.educative.io/answers/how-to-append-data-in-blob-storage-in-azure-using-python

    Login or Signup to reply.
  2. Considering you are calling the same code to append the data, the issue is with the following line of code:

    append_blob_service.create_blob('mycontainer', 'myappendblob')
    

    If you read the documentation for create_blob method, you will notice the following:

    Creates a blob or overrides an existing blob. Use if_none_match=* to
    prevent overriding an existing blob.

    So essentially you are overriding the blob every time you call your code.

    You should call this method with if_none_match="*" as the documentation suggests. If the blob exists, your code will throw an exception which you will need to handle.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search