我正在尝试获取s3存储桶文件夹中指定大小的所有文件。如何遍历存储桶并按指定大小过滤文件?我还想返回那些具有正确大小的文件名。
s3 = boto3.client('s3')
s3.list_objects_v2(Bucket = 'my-images')
示例输出为
u'Key': u'detail/01018535.jpg',
u'LastModified': datetime.datetime(2019, 1, 23, 0, 48, 41, tzinfo=tzlocal()),
u'Size': 13535,
u'StorageClass': 'STANDARD'},
{u'ETag': '"cd65991a1c6f118e8b036208a30028a7"',
u'Key': u'detail/0119AF2.jpg',
u'LastModified': datetime.datetime(2019, 1, 10, 17, 17, tzinfo=tzlocal()),
u'Size': 12984,
u'StorageClass': 'STANDARD'}
例如,假设我想要一个大小为12984的搜索。然后,它将返回“Key”
发布于 2019-04-20 03:25:35
如果您希望使用boto3,我可以使用此函数查找零字节对象。您可以通过过滤特定的大小来调整它以满足您的需要
import boto3
def get_empty_objects(bucket_name, prefixes):
"""
get list of objects from a given s3 prefix recursively
"""
results = []
for prefix in prefixes:
s3client = boto3.client('s3')
paginator = s3client.get_paginator("list_objects_v2")
paginator_result = paginator.paginate(
Bucket=bucket_name, Prefix=prefix)
try:
for object in paginator_result.search('Contents'):
if object['Size'] == 0:
results.append("s3://" + bucket_name + "/" + object['Key'])
except Exception as err:
print(">>> Error processing objects of [s3://" + bucket_name +
"/" + prefix + "] - " + str(err))
print(">>> Returning " + str(len(results)) + " objects for [s3://" + bucket_name + "/" + prefix + "]")
return results
用法:
get_empty_objects("mybucket", ["prefix1/", "prefix2/"])
发布于 2019-04-19 12:42:44
您可以使用--query
表达式:
aws s3api list-objects-v2 --bucket my-images --query 'Contents[?Size==`12984`].[Key]' --output text
我将[Key]
放在方括号中,以强制每个值出现在单独的一行中。
此语法适用于Mac命令行。Windows可能需要不同的引号。
有关使用此类表达式的提示,请参阅:JMESPath Tutorial
https://stackoverflow.com/questions/55752427
复制相似问题