如何从s3存储桶中删除空的子文件夹?

我在我的代码中执行了 2 个循环。下面是伪代码。

get the subfolder list in the bucket
Loop through every subfolders
    loop through every objects in a subfolder
        read the objects
        delete the objects (So at the end the subfolder will be empty)
    get the subfolder list again (asuming the empty subfolder also will be deleted and new subfolders can be created by someone)

但结果我得到了一个无限循环,因为子文件夹仍然在存储桶中。所以我正在寻找一个解决方案,在删除子文件夹中的每个对象后删除它。但我找不到解决方案。请提出你的想法

下面是s3文件夹结构

??? bucket
    ??? folder-1
    ??? folder-2
    ??? folder-3

回答

文件夹实际上并不存在于 Amazon S3 中。相反,Key每个对象的(文件名)由对象的完整路径组成。

因此,您只需要遍历给定 Prefix 的每个对象并删除这些对象。

这是 Python 中的一个示例:

import boto3

s3_resource = boto3.resource('s3')

for object in s3_resource.Bucket('bucket-name').objects.filter(Prefix='folder-name/'):
    print('Deleting:', object.key)
    object.delete()

这也将删除子文件夹中的对象,因为它们具有相同的前缀(并且文件夹实际上不存在)。


以上是如何从s3存储桶中删除空的子文件夹?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>