Tag Archives: BOTO3

HOW TO CHECK IF A KEY EXISTS IN S3 BUCKET USING BOTO3 ?

How to check if a key exists in s3 bucket using boto3?

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 are 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.