Delete Object from S3 using Boto3 Library in Python



In this article, we will see how to delete an object from S3 using Boto 3 library of Python.

Example − Delete test.zip from Bucket_1/testfolder of S3

Approach/Algorithm to solve this problem

Step 1 − Import boto3 and botocore exceptions to handle exceptions.

Step 2 − s3_files_path is parameter in function.

Step 3 − Validate the s3_files_path is passed in AWS format as s3://bucket_name/key.

Step 4 − Create an AWS session using boto3 library.

Step 5 − Create an AWS resource for S3.

Step 6 − Split the S3 path and perform operations to separate the root bucket name and the object path to delete.

Step 7 − Now, use the function delete_object and pass the bucket name and key to delete.

Step 8 − The object is also a dictionary having all the details of a file. Now, fetch the LastModified detail of each file and compare with the given date timestamp.

Step 9 − Handle the generic exception if something went wrong while deleting the file.

Example

Use the following code to delete an object from S3 −

import boto3
from botocore.exceptions import ClientError

def delete_objects_from_s3(s3_files_path):
   if 's3://' not in s3_files_path:
      raise Exception('Given path is not a valid s3 path.')
   session = boto3.session.Session(profile_name='saml')
   s3_resource = session.resource('s3')
   s3_tokens = s3_files_path.split('/')
   bucket_name = s3_tokens[2]
   object_path = ""
   filename = s3_tokens[len(s3_tokens) - 1]
   print('bucket_name: ' + bucket_name)

   if len(s3_tokens) > 4:
      for tokn in range(3, len(s3_tokens) - 1):
         object_path += s3_tokens[tokn] + "/"
      object_path += filename
   else:
      object_path += filename
   print('object: ' + object_path)
   try:
      result = s3_resource.meta.client.delete_object(Bucket=bucket_name, Key=object_path)
   except ClientError as e:
      raise Exception( "boto3 client error in delete_objects_from_s3 function: " + e.__str__())
   except Exception as e:
      raise Exception( "Unexpected error in delete_objects_from_s3 function of s3 helper: " + e.__str__())

#delete test.zip
print(delete_objects_from_s3("s3://Bucket_1/testfolder/test.zip")

Output

bucket_name: Bucket_1
object: testfolder/test.zip
Updated on: 2021-03-22T07:50:29+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements