5

Using https://github.com/googleapis/google-cloud-python/tree/master/storage or https://github.com/GoogleCloudPlatform/appengine-gcs-client, I can delete a files by specifying its file name, but there seems not to be ways to delete folders.

Is there any ways to delete folders ?

I found this(Google Cloud Storage: How to Delete a folder (recursively) in Python) in stackvoerflow, but this answer simply deletes all the files in the folder, not deleting the folder itself.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Taichi
  • 2,297
  • 6
  • 25
  • 47

2 Answers2

17

The code mentioned in the anwser you referred works, the prefix should look like this:

from google.cloud import storage

storage_client = storage.Client()
bucket = storage_client.get_bucket('my-bucket')

blobs = bucket.list_blobs(prefix='my-folder/')

for blob in blobs:
    blob.delete()
dhauptman
  • 974
  • 7
  • 14
9
from google.cloud import storage
    
def delete_storage_folder(bucket_name, folder):
    """
    This function deletes from GCP Storage

    :param bucket_name: The bucket name in which the file is to be placed
    :param folder: Folder name to be deleted
    :return: returns nothing
    """
    cloud_storage_client = storage.Client()
    bucket = cloud_storage_client.bucket(bucket_name)
    try:
        bucket.delete_blobs(blobs=list(bucket.list_blobs(prefix=folder)))
    except Exception as e:
        print(str(e.message))
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Suyash Rathi
  • 184
  • 2
  • 3