Deleting a bucket

To complete the CRUD operation for the bucket, the last thing we need to do is remove the bucket. This happens through calling the delete() method on our bucket variable, given that it already exists and we are referencing it by name, in the same manner that we created it and uploaded data to it. However, delete() may fail when the bucket is not empty. So, we will use the bucket_objects.all().delete() method to get all of the objects inside the bucket, then apply the delete() operation on them, and finally, delete the bucket:

import boto3s3_resource = boto3.resource("s3")bucket = s3_resource.Bucket("my_first_bucket")bucket.objects.all().delete()bucket.delete()

Get Hands-On Enterprise Automation with Python. now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.