如何从S3存储桶中的文件夹中删除带后缀的图像

时间:2019-03-08 07:25:11

标签: amazon-web-services amazon-s3 boto3

我在s3上存储了多种尺寸的图像。 例如image100_100,image200_200,image300_150;

我想从文件夹中删除图像的特定大小,例如后缀为200_200的图像。该文件夹中有很多图像,如何删除这些图像?

2 个答案:

答案 0 :(得分:0)

最简单的方法是编写Python脚本,类似于:

import boto3

BUCKET = 'my-bucket'
PREFIX = '' # eg 'images/'

s3_client = boto3.client('s3', region_name='ap-southeast-2')

# Get a list of objects
list_response = s3_client.list_objects_v2(Bucket = BUCKET, Prefix = PREFIX)

while True:
    # Find desired objects to delete
    objects = [{'Key':object['Key']} for object in list_response['Contents'] if object['Key'].endswith('200_200')]
    print ('Deleting:', objects)

    # Delete objects
    if len(objects) > 0:
        delete_response = s3_client.delete_objects(
            Bucket=BUCKET,
            Delete={'Objects': objects}
        )

    # Next page
    if list_response['IsTruncated']:
        list_response = s3_client.list_objects_v2(
            Bucket = BUCKET,
            Prefix = PREFIX,
            ContinuationToken=list_reponse['NextContinuationToken'])
    else:
        break

答案 1 :(得分:0)

使用AWS命令行界面(AWS CLI):

aws s3 rm s3://Path/To/Dir/ --recursive --exclude "*" --include "*200_200"

我们首先排除所有内容,然后包括需要删除的内容。这是一种模仿Linux中rm -r "*200_200"命令行为的解决方法。