How to delete a file in AWS S3 using boto3 and Python

To delete a file inside an AWS S3 Bucket using Python then you will need to use the delete_object function of boto3.

Below are 3 examples to delete an S3 file.

You can use any of the 3 options since it does the same thing. It will delete the file in S3 with the key of s3_folder/file.txt inside the S3 bucket named radishlogic-bucket using Python boto3.

Just use the method you are comfortable with.


Note: The examples below only uses a .txt file but you can use any file type such as .mp4, .docx, .odt, etc. You can even use object keys without filename extensions.


Option 1: boto3 S3 Client Delete Object

import boto3

# Initialize boto3 to use the S3 client.
s3_client = boto3.client('s3')

# Delete the file inside the S3 Bucket
s3_response = s3_client.delete_object(
    Bucket='radishlogic-bucket',
    Key='s3_folder/file.txt'
)

Option 2: boto3 S3 resource Delete Object via S3 object

import boto3

# Initialize boto3 to use S3 resource
s3_resource = boto3.resource('s3')

# Get the object from the S3 Bucket
s3_object = s3_resource.Object(
    bucket_name='radishlogic-bucket',
    key='s3_folder/file.txt'
)

# Delete the object
s3_object.delete()

Option 3: boto3 S3 resource Delete File via S3 bucket

This is basically the same as Option 2, the only difference is that it first creates a variable that represents the S3 Bucket (s3_bucket), then from that variable, it gets the S3 file/object (s3_object) and deletes it.

import boto3

# Initialize boto3 to use S3 resource
s3_resource = boto3.resource('s3')

# Get the S3 Bucket
s3_bucket = s3_resource.Bucket(name='radishlogic-bucket')

# Get the S3 Object from the S3 Bucket
s3_object = s3_bucket.Object(key='s3_folder/file.txt')

# Delete the object
s3_object.delete()

Shortening the code for boto3 S3 resource delete object

You can shorten the code to delete an S3 object by chaining the delete() function when you get the S3 object. Below are shortened versions of using both alternatives to delete an S3 file using boto3 resource.

Option 2 shortened

import boto3

# Initialize boto3 to use S3 resource
s3_resource = boto3.resource('s3')

# Get the object from the S3 Bucket and delete it
s3_object = s3_resource.Object(
    bucket_name='radishlogic-bucket',
    key='s3_folder/file.txt'
).delete()

Option 3 shortened

import boto3

# Initialize boto3 to use S3 resource
s3_resource = boto3.resource('s3')

# Get the S3 Bucket
s3_bucket = s3_resource.Bucket(name='radishlogic-bucket')

# Get the S3 Object from the S3 Bucket and delete it
s3_object = s3_bucket.Object(key='s3_folder/file.txt').delete()

We hope the above tutorial helps you delete a file/objects in an S3 Bucket using Python and boto3.

Let us know your experience in the comments below.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.