Narasimha Theja Rao
Narasimha Theja Rao

Reputation: 199

Delete files under S3 bucket recursively without deleting folders using python

I'm getting error, When i try to delete all files under specific folder Problem is here ['Key': 'testpart1/.'] Also i would like to delete 30 days older file, please help me with script

import boto3
s3 = boto3.resource('s3')
my_bucket = s3.Bucket('my-bucket')

response = my_bucket.delete_objects(
    Delete={
        'Objects': [
            {
                'Key': 'testpart1/*.*'   # the_name of_your_file
            }
        ]
    }

Upvotes: 1

Views: 2556

Answers (1)

Gautam Krishna R
Gautam Krishna R

Reputation: 2645

The code below will delete all files under the prefix recursively:

import boto3
s3 = boto3.resource('s3')
my_bucket = s3.Bucket('my-bucket')

response = my_bucket.objects.filter(Prefix="testpart1/").delete()

Please check https://stackoverflow.com/a/59146547/4214976 to filter out the object based on date.

Upvotes: 2

Related Questions