0

I want to check whether folder or directory exist in give s3 bucket, if exist i want delete folder from s3 bucket using python code.

example for : s3:/bucket124/test

Here "bucket124" is bucket and "test" is folder contains some files like test.txt test1.txt

I want to delete folder "test" from my s3 bucket.

Sai
  • 1,075
  • 5
  • 31
  • 58
  • 1
    What have you tried? Where did it fail? – Ofer Sadan May 22 '18 at 08:00
  • import boto3 from botocore.errorfactory import ClientError from boto.s3.connection import S3Connection, Bucket, Key s3 = boto3.client('s3', aws_access_key_id='AKIA', aws_secret_access_key='vfEn') try: bucket = Bucket('AKIA', 'vfEn') s3.head_object(Bucket='bucket124', Key='test') k = boto3.Key(bucket =bucket124, name='test') k.delete() except ClientError: print("file not found") – Sai May 22 '18 at 08:06
  • I tried above code – Sai May 22 '18 at 08:07
  • 1
    edit it into your question. make life easy for those trying to help you if you want actual help – Ofer Sadan May 22 '18 at 08:09

1 Answers1

0

Here is how you will do that,

import boto3

s3 = boto3.resource('s3')
bucket=s3.Bucket('mausamrest');
obj = s3.Object('mausamrest','test/hello')
counter=0

for key in bucket.objects.filter(Prefix='test/hello/'):
    counter=counter+1

if(counter!=0):
    obj.delete()
print(counter)

mausamrest is the bucket and test/hello/ is the directory you want to check for items , but take care of one thing that after checking you have to delete test/hello instead of test/hello/ to delete a particular sub folder and hence the keyname in 5th line is test/hello

Mausam Sharma
  • 852
  • 5
  • 10
  • Consider renaming `obj` of `for`-loop to something else to avoid *confusion*. Are you sure that this method won't be plagued by the issue described [here](https://stackoverflow.com/a/11427712/3679900) (i.e. paths like `test/hello-this-should-not-have-been-deleted/` also get deleted)? – y2k-shubham Aug 07 '18 at 08:56