Boto3 S3,按上次修改时间对存储区进行排序 [英] Boto3 S3, sort bucket by last modified

查看:179
本文介绍了Boto3 S3,按上次修改时间对存储区进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用Boto3从S3中获取项目列表,但我希望它以相反的顺序返回它,而不是返回默认的排序顺序(降序).

I need to fetch a list of items from S3 using Boto3, but instead of returning default sort order (descending) I want it to return it via reverse order.

我知道您可以通过awscli做到这一点:

I know you can do it via awscli:

aws s3api list-objects --bucket mybucketfoo --query "reverse(sort_by(Contents,&LastModified))"

及其可通过UI控制台执行(不确定是在客户端还是在服务器端完成)

and its doable via the UI console (not sure if this is done client side or server side)

我似乎看不到如何在Boto3中做到这一点.

I cant seem to see how to do this in Boto3.

我目前正在获取所有文件,然后进行排序...但是这似乎有些过分,尤其是当我只关心大约10个左右的最新文件时.

I am currently fetching all the files, and then sorting...but that seems overkill, especially if I only care about the 10 or so most recent files.

过滤器系统似乎只接受s3的前缀,

The filter system seems to only accept the Prefix for s3, nothing else.

推荐答案

我对以下@helloV发表的内容做了一些细微改动.它不是100%最佳的,但它可以解决boto3截至目前的局限性.

I did a small variation of what @helloV posted below. its not 100% optimum, but it gets the job done with the limitations boto3 has as of this time.

s3 = boto3.resource('s3')
my_bucket = s3.Bucket('myBucket')
unsorted = []
for file in my_bucket.objects.filter():
   unsorted.append(file)

files = [obj.key for obj in sorted(unsorted, key=get_last_modified, 
    reverse=True)][0:9]

这篇关于Boto3 S3,按上次修改时间对存储区进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆