Fix Python – Amazon S3 boto – how to delete folder?

Question

Asked By – wade huang

I created a folder in s3 named “test” and I pushed “test_1.jpg”, “test_2.jpg” into “test”.

How can I use boto to delete folder “test”?

Now we will see solution for issue: Amazon S3 boto – how to delete folder?


Answer

There are no folders in S3. Instead, the keys form a flat namespace. However a key with slashes in its name shows specially in some programs, including the AWS console (see for example Amazon S3 boto – how to create a folder?).

Instead of deleting “a directory”, you can (and have to) list files by prefix and delete. In essence:

for key in bucket.list(prefix='your/directory/'):
    key.delete()

However the other accomplished answers on this page feature more efficient approaches.


Notice that the prefix is just searched using dummy string search. If the prefix were your/directory, that is, without the trailing slash appended, the program would also happily delete your/directory-that-you-wanted-to-remove-is-definitely-not-t‌​his-one.

For more information, see S3 boto list keys sometimes returns directory key.

This question is answered By – Antti Haapala — Слава Україні

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0