Delete all versions of an object in S3 using python?

后端 未结 9 2015
既然无缘
既然无缘 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 17:45

    You can use object_versions.

    def delete_all_versions(bucket_name: str, prefix: str):
        s3 = boto3.resource('s3')
        bucket = s3.Bucket(bucket_name)
        if prefix is None:
            bucket.object_versions.delete()
        else:
            bucket.object_versions.filter(Prefix=prefix).delete()
    
    delete_all_versions("my_bucket", None) # empties the entire bucket
    delete_all_versions("my_bucket", "my_prefix/") # deletes all objects matching the prefix (can be only one if only one matches)
    

提交回复
热议问题