Reputation: 51
I have a subfolder that I want to delete from an S3 bucket.
I want to delete the subfolder folder2
mybucket/folder1/folder2/folder3
The name of folder2 will vary, so I'm trying to loop through the objects in folder1 and somehow delete the second level folder. The current code I have works ONLY if the folder3 (subfolder of folder2) doesn't exist.
bucket = s3.Bucket(mybucket)
result = client.list_objects_v2(Bucket=mybucket, Delimiter='/', Prefix="folder1/")
for object in result.get('CommonPrefixes'):
subfolder = object.get('Prefix')
s3.Object(mybucket,subfolder).delete()
Upvotes: 1
Views: 259
Reputation: 93
The thing you have to remember about Amazon S3 is that folders, in the sense you think of them, don't exist. They're not real. S3 is object storage, which means it thinks in objects, not files. The fact that the console renders things that look like filepaths with subfolders and so forth is just for convenience.
So instead of trying to delete a folder, you want to delete all files whose names begin with that prefix.
Upvotes: 3