[英]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.