简体   繁体   中英

Demonstrate how to delete a particular key or keys from an S3 bucket using boto3

This boto3 function allows for deletion of a list of keys from an S3 bucket. Please could you demonstrate an example of how to use it with:

  1. a single key to be deleted.
  2. a list of multiple keys to be deleted.

With thanks.

delete_objects(**kwargs)
This operation enables you to delete multiple objects from a bucket using a  single HTTP request. You may specify up to 1000 keys.

Request Syntax

response = bucket.delete_objects(
    Delete={
        'Objects': [
            {
                'Key': 'string',
                'VersionId': 'string'
            },
        ],
        'Quiet': True|False
    },
    MFA='string',
    RequestPayer='requester'
)

Delete one object:

response = bucket.delete_objects(
    Delete={
        'Objects': [
            {
                'Key': 'myObjectKey'
            }
        ]
    }
)

Delete two objects:

response = bucket.delete_objects(
    Delete={
        'Objects': [
            {
                'Key': 'myFirstObjectKey'
            },
            {
                'Key': 'mySecondObjectKey'
            }
        ]
    }
)

I feel like the documentation (which you linked) makes this extremely obvious. I'm curious as to how you found the documentation confusing.

Answer:

# Delete key(s)
forDeletion = [{'Key':'IMG_20160807_150118.jpg'}, {'Key':'IMG_20160807_150124.jpg'}]
response = bucket.delete_objects(Delete={'Objects': forDeletion})

for elem in response.get('Deleted'):
    print(elem['Key']) 

Output:

IMG_20160807_150118.jpg
IMG_20160807_150124.jpg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM