What is the fastest way to empty s3 bucket using boto3?

Tushar Niras picture Tushar Niras · Apr 10, 2017 · Viewed 25.7k times · Source

I was thinking about deleting and then re-creating bucket (bad option which I realised later).

Then how can delete all objects from the bucket?

I tried this : http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Bucket.delete_objects

But it deletes multiple objects not all.

can you suggest what is the best way to empty bucket ?

Answer

mootmoot picture mootmoot · Apr 10, 2017

Just use aws cli.

aws s3 rm s3://mybucket --recursive

Well, for longer answer if you insists to use boto3. This will send a delete marker to s3. No folder handling required. bucket.Object.all will create a iterator that not limit to 1K .

import boto3    
s3 = boto3.resource('s3')
bucket = s3.Bucket('my-bucket')
# suggested by Jordon Philips 
bucket.objects.all().delete()