Checking for the Existence of an Object in S3

Overview

This page explains how to check for the existence of an object in S3 using Python.

Method Using boto3

To check using boto3.resource, you can use the following code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
s3 = boto3.resource('s3')
try:
    s3.Object('bucket_name', 'object_name').load()
    print("True")
except ClientError as e:
    error_code = e.response['Error']['Code']
    if error_code == '404':
        print("Object does not exist.")
    else:
        print(f"An error occurred: {e}")

If you’re using boto3.client, you can check with this code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
s3 = boto3.client('s3')
try:
    s3.head_object(Bucket='bucket_name', Key='object_name')
    print("True")
except ClientError as e:
    error_code = e.response['Error']['Code']
    if error_code == '404':
        print("Object does not exist.")
    else:
        print(f"An error occurred: {e}")

Reference