Delete an S3 directory with Python

In a previous example we saw how we could delete a file from S3 with Python, in this case we are going to do something similar, which is to delete a directory from S3 with Python.

Although, in the case of deleting files we had the .delete() method, the TinyS3 library does not offer us a method that allows deleting a directory, so we will have to implement it ourselves.

The idea of ​​deleting a file from S3 with Python what it seeks is to delete each and every one of the files in the directory, to, in the end, delete the directory itself. Since if we try to delete a directory that has content it will give us an error.

The first thing to be able to delete an S3 directory with Python will connect us to the Amazon S3 system using the private key and secret.

S3_ACCESS_KEY = 'BAKIBAKI678H67HGA'
S3_SECRET_KEY = '+vpOpILD+E9872AialendX0Ui123CKCKCKw'
BUCKET = '/vcp-test'
DIRECTORY = '/mydirectory/'

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

What we are going to do is list the directory that we want to delete. For this we are going to use the <.list() method

list = conn.list(DIRECTORY,BUCKET)

We see that not only must we indicate the name of the directory to be listed, but we must also indicate the bucket that contains it.

Now we will begin to go through the files that the directory has.

for file in list:
    conn.delete(file['key'])

For each of the files we are going to execute the .delete() method, which will delete said file. It is important to know that we have to use the meta information of the key to pass it as a parameter to the .delete() method

Once we have deleted all the files in the directory, we will only have to delete the directory, now empty, using the same method.

conn.delete(DIRECTORY)

In this way we will have already managed to delete an S3 directory with Python.