简体   繁体   English

如何从 S3 存储桶中仅获取子文件夹名称

[英]How to get only the sub folder names from a S3 bucket

I'm having a S3 bucket, which contains many sub folders.我有一个 S3 存储桶,其中包含许多子文件夹。 let's say,比方说,

'test-bucket'
-->'photos'
    -->2020
    -->2019
    -->2018
    ...

In the 'test-bucket' there is a sub folder called 'photos' and in the photos folder there may have multiple sub folders.在“测试桶”中有一个名为“照片”的子文件夹,在照片文件夹中可能有多个子文件夹。

So i need to loop through photos bucket and get only the photos older than 2 years (ie from 2018).所以我需要遍历照片桶并只获取超过 2 年的照片(即从 2018 年开始)。 This is my code below using python library boto3.这是我下面使用 python 库 boto3 的代码。

current_year = datetime.datetime.now().year
client.list_objects_v2(Bucket='test-bucket',Prefix = 'photos/'+str(current_year-3),MaxKeys=1000 )

But this only returns 2018 data only.但这仅返回 2018 年的数据。 Suggest an idea to loop through entire years which are older than 2 years.提出一个想法来循环超过 2 年的整年。 Thanks in advance提前致谢

You can obtain the folder names by using ListObjects() while passing a Delimiter value.您可以在传递Delimiter值时使用ListObjects()获取文件夹名称。 It then returns the list of folders as CommonPrefixes .然后它将文件夹列表作为CommonPrefixes返回。

Here's some sample code:这是一些示例代码:

import boto3

s3_client = boto3.client('s3')
objects = s3_client.list_objects_v2(Bucket='my-bucket', Delimiter='/', Prefix ='photos/')

for prefix in objects['CommonPrefixes']:
    print(prefix['Prefix'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 仅从 s3 存储桶文件夹中获取文件名 - Get only file names from s3 bucket folder 如何仅从 S3 存储桶中的特定路径文件夹(或路径前缀)获取文件 - How to get only files only from specific path folder (or path prefix) in an S3 bucket 如何从S3存储桶中的文件夹中获取对象 - How to get objects from a folder in an S3 bucket 从 S3 存储桶获取文件夹内容 - Get folder content from S3 bucket 如何从 S3 存储桶和所有子文件夹中检索文件名 - How to retrieve file names from S3 bucket and all of the subfolders 如何从 python 脚本在 s3 存储桶上创建文件夹? - How to create a folder on s3 bucket from python script? 如何使用 python 列出 S3 存储桶文件夹中的文件 - how to list files from a S3 bucket folder using python 将文件从一个 AWS s3 存储桶/文件夹复制到另一个 AWS/S3 文件夹,并通过 python 在数据块上保留最深的子文件夹名称 - copy files from one AWS s3 bucket/folder to another AWS/S3 folder and also keep the deepest sub-folder name by pythons on databricks 如何将子文件夹移动到同一个 s3 存储桶 boto3 中的另一个主文件夹? - How can I move a sub-folder to another main folder within same s3 bucket boto3? 如何从 url 视频中获取图像(存储在 s3 存储桶中) - how to get an image from the url video (stored on s3 bucket)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM