Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to use Boto3 library in Python to delete an object from S3 using AWS Resource?
In this article, we will see how to delete an object from S3 using the Boto3 library of Python. Boto3 is the AWS SDK for Python that provides an easy way to integrate Python applications with AWS services like S3.
Example ? Delete test.zip from Bucket_1/testfolder of S3
Prerequisites
Before using Boto3, you need to configure your AWS credentials. You can do this by installing the AWS CLI and running aws configure, or by setting up credential files.
Approach/Algorithm
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 ? Use the function delete_object and pass the bucket name and key to delete.
Step 8 ? 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)
print("Object deleted successfully")
return result
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
delete_objects_from_s3("s3://Bucket_1/testfolder/test.zip")
Output
bucket_name: Bucket_1 object: testfolder/test.zip Object deleted successfully
Simplified Alternative Approach
For simpler use cases, you can directly use the S3 client without creating a session ?
import boto3
from botocore.exceptions import ClientError
def delete_s3_object_simple(bucket_name, object_key):
s3_client = boto3.client('s3')
try:
response = s3_client.delete_object(Bucket=bucket_name, Key=object_key)
print(f"Successfully deleted {object_key} from bucket {bucket_name}")
return response
except ClientError as e:
print(f"Error deleting object: {e}")
return None
# Example usage
delete_s3_object_simple("Bucket_1", "testfolder/test.zip")
Key Points
- The
delete_object()method requires the bucket name and object key (path) - AWS credentials must be properly configured before using Boto3
- The function returns a response dictionary with metadata about the deletion
- Always handle exceptions when working with AWS services
Conclusion
Using Boto3's delete_object() method provides a straightforward way to delete S3 objects programmatically. Always ensure proper error handling and valid AWS credentials for successful operations.
