amazon-web-services - 如何从 s3 存储桶中删除空子文件夹?

标签 amazon-web-services amazon-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(文件名)由对象的完整路径组成。

因此,您只需循环遍历给定前缀的每个对象并删除这些对象即可。

这是一个 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()

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

关于amazon-web-services - 如何从 s3 存储桶中删除空子文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67945783/

相关文章:

python - 使用无服务器框架将 API 添加到使用计划

node.js - 在 Amazon CentOS 上使用 yum 安装 Node.js - libssl 错误

java - AWS SDK for S3 中的 TransferManager 是否在执行异步 I/O?

amazon-web-services - 将 S3 对象 ID 传递给 EC2 实例的最佳方式?

amazon-web-services - 通过 AWS CLI 将文件上传到 S3 时出现 "Broken pipe"

node.js - "Cannot read property ' 预签名-过期 ' of undefined"

c# - .Net Core 3.1 异步控制台应用程序在 VS 外部运行时挂起

amazon-web-services - 增加 aws beanstalk 中 .net core api 的请求大小限制

amazon-web-services - 使用 AWS Kinesis 上传大文件

amazon-web-services - AWS S3 - 编辑存储桶策略的权限