pythonamazon-web-servicesamazon-s3boto3

check if a key exists in a bucket in s3 using boto3


I would like to know if a key exists in boto3. I can loop the bucket contents and check the key if it matches.

But that seems longer and an overkill. Boto3 official docs explicitly state how to do this.

May be I am missing the obvious. Can anybody point me how I can achieve this.


Solution

  • Boto 2's boto.s3.key.Key object used to have an exists method that checked if the key existed on S3 by doing a HEAD request and looking at the the result, but it seems that that no longer exists. You have to do it yourself:

    import boto3
    import botocore
    
    s3 = boto3.resource('s3')
    
    try:
        s3.Object('my-bucket', 'dootdoot.jpg').load()
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] == "404":
            # The object does not exist.
            ...
        else:
            # Something else has gone wrong.
            raise
    else:
        # The object does exist.
        ...
    

    load() does a HEAD request for a single key, which is fast, even if the object in question is large or you have many objects in your bucket.

    Of course, you might be checking if the object exists because you're planning on using it. If that is the case, you can just forget about the load() and do a get() or download_file() directly, then handle the error case there.