Search code examples
pythonamazon-web-servicesamazon-s3boto3bucket

How to check if folder in an Amazon S3 bucket is empty? - boto3 python


I have an Amazon S3 bucket my-bucket and folder my-folder.

I want my script to execute different results depending on the existence (or lack thereof) of files with my-folder. Thus, I want to check the condition of whether or not my-folder is empty and does not contain any files.

How would I go about doing this?

Unfortunately, I've tried searching the documentation and other Stack Overflow posts but could not seem to find anything similar.


Solution

  • You can count the number of objects in the prefix:

    import boto3
    
    BUCKET_NAME = 'bucket'
    FOLDER_NAME = 'my-folder/'
    
    s3_resource = boto3.resource('s3')
    
    bucket = s3_resource.Bucket(BUCKET_NAME)
    
    count = bucket.objects.filter(Prefix=FOLDER_NAME)
    
    print(len(list(count)))