Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in AWS by (19.1k points)

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.

Maybe I am missing the obvious. Can anybody point to me how I can achieve this?

1 Answer

0 votes
by (44.4k points)

You can do this:

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.

    ...

A HEAD request for a single key is done by load(), this is fast even though there is a big object or there are many objects in your bucket.

If you are checking if the object exists so that you can use it, then you just do a get() or download_file() directly instead of load().

You will find out more about the Amazon S3 on AWS S3.

Related questions

0 votes
1 answer
asked Jul 23, 2019 in AWS by yuvraj (19.1k points)
Want to get 50% Hike on your Salary?

Learn how we helped 50,000+ professionals like you !

0 votes
1 answer
asked Jul 23, 2019 in AWS by yuvraj (19.1k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...