Reputation: 632
This would delete all objects in a s3 bucket
s3_b=boto3.client("s3")
objects=s3_b.list_objects(Bucket="bucket_name")["Contents"]
for obj in objects:
s3_b.delete_object(Bucket='bucket_name',Key=obj["Key"])
Is there a similar way to delete an object with a particular key path like s3://bucket_name/folder1/folder2/folder3/folder4
, where I want to delete all the objects within folder4
Edit:
Would it be possible to delete objects in two different paths within the same loop
Eg: 'folder1/folder2/folder3/folder4'
and 'folder1/folder2/folder3/folder5'
Upvotes: 2
Views: 1989
Reputation: 238209
You can use filter. For example:
import boto3
s3r = boto3.resource('s3')
bucket = s3r.Bucket('bucket_name')
for object in bucket.objects.filter(Prefix='folder1/folder2/folder3/folder4'):
print(object)
#object.delete() # uncomment to delete
Upvotes: 1
Reputation: 663
You could use .delete_objects
and pass the objects list as parameter:
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.delete_objects
Upvotes: 1