dragonachu
dragonachu

Reputation: 551

S3 Delete files inside a folder using boto3

How can we delete files inside an S3 Folder using boto3?

P.S - Only files should be deleted, folder should remain.

Upvotes: 15

Views: 51095

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 270144

You would have to use delete_object():

import boto3

s3_client = boto3.client('s3')

response = s3_client.delete_object(
    Bucket='my-bucket',
    Key='invoices/January.pdf'
)

If you are asking how to delete ALL files within a folder, then you would need to loop through all objects with a given Prefix:

import boto3

s3_client = boto3.client('s3')

BUCKET = 'my-bucket'
PREFIX = 'folder1/'

response = s3_client.list_objects_v2(Bucket=BUCKET, Prefix=PREFIX)

for object in response['Contents']:
    print('Deleting', object['Key'])
    s3_client.delete_object(Bucket=BUCKET, Key=object['Key'])

Also, please note that folders do not actually exist in Amazon S3. The Key (filename) of an object contains the full path of the object. If necessary, you can create a zero-length file with the name of a folder to make the folder 'appear', but this is not necessary. Merely creating a folder in a given path will make any subfolders sort of 'appear', but they will 'disappear' when the object is deleted (since folders don't actually exist).

Upvotes: 62

Related Questions