使用Python向Azure Blob存储追加数据时旧数据被覆盖的问题求助
Ah, I spot the problem right away! Every time you run your code, you're calling create_blob('mycontainer', 'myappendblob') — and if that append blob already exists, this method completely overwrites it. That's why your old data gets wiped out before you add new content.
Append blobs do need to be created before you can append to them, but you only need to create them once. Here's how to adjust your code to safely append data without overwriting:
Option 1: Check if the blob exists first
Manually verify the blob's existence before creating it. This gives you explicit control:
from azure.storage.blob import AppendBlobService # Initialize the service append_blob_service = AppendBlobService(account_name='myaccount', account_key='mykey') append_blob_service.create_container('mycontainer') # Only create the blob if it doesn't already exist if not append_blob_service.exists('mycontainer', 'myappendblob'): append_blob_service.create_blob('mycontainer', 'myappendblob') # Append new data to the existing (or newly created) blob append_blob_service.append_blob_from_text('mycontainer', 'myappendblob', u'Hello again, world!') # Verify the result append_blob = append_blob_service.get_blob_to_text('mycontainer', 'myappendblob') print(append_blob.content)
Option 2: Use the safer create_blob_if_not_exists method
This built-in method handles the existence check automatically, so you don't have to write conditional logic:
from azure.storage.blob import AppendBlobService append_blob_service = AppendBlobService(account_name='myaccount', account_key='mykey') append_blob_service.create_container('mycontainer') # Safely creates the blob only if it's missing — no overwrite occurs append_blob_service.create_blob_if_not_exists('mycontainer', 'myappendblob') # Append your new content append_blob_service.append_blob_from_text('mycontainer', 'myappendblob', u'Another line added to the append blob!') # Check the updated content append_blob = append_blob_service.get_blob_to_text('mycontainer', 'myappendblob') print(append_blob.content)
Either approach will ensure that subsequent runs of your code add new data to the end of the append blob, instead of replacing the entire blob.
内容的提问来源于stack exchange,提问作者SanjanaSanju

