Amazon S3 boto - how to delete folder?

后端 未结 6 809
我寻月下人不归
我寻月下人不归 2020-11-30 23:40

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\"?

6条回答
  •  情深已故
    2020-12-01 00:06

    I feel that it's been a while and boto3 has a few different ways of accomplishing this goal. This assumes you want to delete the test "folder" and all of its objects Here is one way:

    s3 = boto3.resource('s3')
    objects_to_delete = s3.meta.client.list_objects(Bucket="MyBucket", Prefix="myfolder/test/")
    
    delete_keys = {'Objects' : []}
    delete_keys['Objects'] = [{'Key' : k} for k in [obj['Key'] for obj in objects_to_delete.get('Contents', [])]]
    
    s3.meta.client.delete_objects(Bucket="MyBucket", Delete=delete_keys)
    

    This should make two requests, one to fetch the objects in the folder, the second to delete all objects in said folder.

    https://boto3.readthedocs.org/en/latest/reference/services/s3.html#S3.Client.delete_objects

提交回复
热议问题