Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Cloud Storage: How to Delete a folder (recursively) in Python

I am trying to delete a folder in GCS and its all content (including sub-directories) with its Python library. Also I understand GCS doesn't really have folders (but prefix?) but I am wondering how I can do that?

I tested this code:

from google.cloud import storage

def delete_blob(bucket_name, blob_name):
    """Deletes a blob from the bucket."""
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)
    blob = bucket.blob(blob_name)

    blob.delete()

delete_blob('mybucket', 'top_folder/sub_folder/test.txt')
delete_blob('mybucket', 'top_folder/sub_folder/')

The first call to delete_blob worked but not the 2nd one. What can I delete a folder recursively?

like image 634
kee Avatar asked Oct 13 '18 05:10

kee


People also ask

How do I delete a folder in Google Cloud Storage?

Navigate to the objects, which may be located in a folder. Click the checkbox for each object you want to delete. You can also click the checkbox for folders, which will delete all objects contained in that folder. Click the Delete button.

How do I delete files from Google cloud?

To delete your Google Drive files, move them to the trash. Files in trash will be automatically deleted after 30 days. You can restore files from your trash before the 30-day time window. You can also permanently delete them to empty your trash.


1 Answers

To delete everything starting with a certain prefix (for example, a directory name), you can iterate over a list:

storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blobs = bucket.list_blobs(prefix='some/directory')
for blob in blobs:
  blob.delete()

Note that for very large buckets with millions or billions of objects, this may not be a very fast process. For that, you'll want to do something more complex, such as deleting in multiple threads or using lifecycle configuration rules to arrange for the objects to be deleted.

like image 189
Brandon Yarbrough Avatar answered Sep 20 '22 19:09

Brandon Yarbrough