0

When I try to delete a specific folder in the GCS bucket, "Sample", it deletes all the folder names starting with "Sample" (e.g. like "Sample","Sample1","Sample2").

The answer available here does not filter enough for my purposes

Can someone suggest how to fix this?

  from google.cloud import storage

  storage_client = storage.Client()
  bucket = storage_client.get_bucket('bucket name')
  blobs = bucket.list_blobs(prefix='Sample')
  for blob in blobs:
     blob.delete()
davetherock
  • 224
  • 1
  • 2
  • 12
NMB
  • 39
  • 7
  • It's not really clear what's not working the way you expect. We can't see the contents of your bucket and we can't see the values of the variables in your code, so we don't really know what's wrong. Please edit the question to add enough information that anyone can use the better understand what you're doing and how to reproduce the behavior you find to be a problem. – Doug Stevenson Jun 16 '23 at 16:06
  • My issue is when I run the above code to delete a folder called Sample it deletes all the folder names starting with sample like Sample,Sample1,Sample2. But I just need Sample folder to be deleted – NMB Jun 16 '23 at 16:07

1 Answers1

2

The reason that you are deleting multiple folders is because of the line bucket.list_blobs(prefix="Sample"). This returns all folders that start with "Sample".

You could add additional filters to your list_blobs() method call. The available ones can be seen on GitHub here.

Alternatively, you could add a decision rule into your "for" loop, like so

for blob in blobs:
   if blob.name == "Sample": # Now .delete() is not always called 
      blob.delete()
davetherock
  • 224
  • 1
  • 2
  • 12
  • Thank you so much dave! But I got the answer just we have to put a "/" after the specific folder name then it wont delete anything else :-) code given below : from google.cloud import storage storage_client = storage.Client() bucket = storage_client.get_bucket('bucket name') blobs = bucket.list_blobs(prefix='Sample/') for blob in blobs: blob.delete() – NMB Jun 16 '23 at 16:49