Delete all versions of an object in S3 using python?

后端 未结 9 2026
既然无缘
既然无缘 2021-02-05 17:28

I have a versioned bucket and would like to delete the object (and all of its versions) from the bucket. However, when I try to delete the object from the console, S3 simply add

9条回答
  •  情话喂你
    2021-02-05 18:04

    Fewer line solution.

    import boto3
    
    def delete_versions(bucket, objects=None): # `objects` is either list of str or None
      bucket = boto3.resource('s3').Bucket(bucket)
      if objects: # delete specified objects
        [version.delete() for version in bucket.object_versions.all() if version.object_key in objects]
      else: # or delete all objects in `bucket`
        [version.delete() for version in bucket.object_versions.all()]
    

提交回复
热议问题