Search code examples
pythonpython-2.7boto3

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


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 ?


Solution

  • Use the Amazon Web Services CLI.

    aws s3 rm s3://mybucket --recursive
    

    For a longer answer, if you insists to use boto3, this will send a delete marker to s3, with 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()