Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete GCS folder from Python?

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.

like image 270
Taichi Avatar asked Nov 06 '18 03:11

Taichi


People also ask

How do I delete GCS?

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 Python files?

remove() method in Python can be used to remove files, and the os. rmdir() method can be used to delete an empty folder. The shutil. rmtree() method can be used to delete a folder along with all of its files.

How do I delete a folder in Jupyter notebook?

shutil. rmtree('/your/folder/path/') #deletes a directory and all its contents.


2 Answers

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()
like image 53
dhauptman Avatar answered Oct 22 '22 20:10

dhauptman


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))
like image 41
Suyash Rathi Avatar answered Oct 22 '22 20:10

Suyash Rathi