Delete a file from S3 with Python

In this example we are going to continue using the tinys3 library to be able to delete a file from S3 with Python. The first thing we will do is import the tinys3 library into our program.

import tinys3

Once the library is imported we can use the tinys3 object to make a connection with Amazon S3. When making a connection we will need to have the access code and the secret. Which will be codes similar to the ones you can see below.

S3_ACCESS_KEY = 'BAKIBAKI678H67HGA'
S3_SECRET_KEY = '+vpOpILD+E9872AialendX0Ui123CKCKCKw'

The .Connection() method will be the one that helps us make the connection against S3. We pass the two keys to this method, optionally the bucket on which we will work and the Amazon region in which we have our S3 deployed.

conn = tinys3.Connection(S3_ACCESS_KEY,S3_SECRET_KEY,'vcp-test',endpoint='s3-eu-west-1.amazonaws.com')

Directly on the new connection object created we have a method called .delete() to which we pass the key of the object to be deleted, as well as the bucket in which it is located in order to delete the file.

BUCKET = '/vcp-test'
filename = 'file.png'
conn.delete(filename,BUCKET)

In this simple way we will have managed to delete an S3 file with Python.

Leave a Comment