7/01/2019

AWS s3 bucket - check folder exist or not by python code

Check certain folder exist in s3 bucket by python ncode


-
#create boto3 instance
s3_client = boto3.client(
        's3',
        aws_access_key_id=ACCESS_KEY,
        aws_secret_access_key=SECRET_KEY,
    )

#check folder exist
try:
        s3_client.get_object(Bucket='s3-bucket-name', Key='folder-name/')
        print('folder exist')
except botocore.exceptions.ClientError as e:
        print('no folder exist')
-

Thank you.


function type is here:
def check_folder_exist(s3_client, bucket_name, folder_name):
    
    try:
        s3_client.get_object(Bucket=bucket_name, Key=folder_name)
        return True
    except botocore.exceptions.ClientError as e:
        return False


If not working above code then try this one as well.
def check_folder_exist(bucket_name, folder_name):
try:
print(bucket_name, folder_name)
result = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=folder_name )
if 'Contents' in result:
return True
else:
return False
except botocore.exceptions.ClientError as e:
print(e)
return False

No comments:

Post a Comment