Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 231
dragonachu Avatar asked Nov 25 '19 06:11

dragonachu


1 Answers

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).

like image 135
John Rotenstein Avatar answered Sep 30 '22 19:09

John Rotenstein