How to Check if an Object Exists in AWS S3 Using Python and Boto3

By Birtchum Thompson | April 5, 2020

It is often necessary to programmatically check if an object exists before performing an action such as deleting the object, updating, the object, or invalidating an AWS CloudFront object. This tutorial will demonstrate how to check if an object exists in an S3 bucket using Python and Boto3.

Boto3, AWS’s Python SDK, does not provide a straight-forward method of doing this, but a simple HEAD request for the object will reveal if it exists or not. If the object does not exist in the S3 bucket, a ClientError will be raised and the response will contain a 404 error code. The following script will return True if the object exists, return False if it receives the 404 error code, or return the error code if something else went wrong.

 Python
Share this Content

Join the Discussion

Also Read

AWS CloudFront logo on grey background
Invalidate CloudFront Objects with Boto3

Learn to Invalidate CloudFront objects by paths with Boto3.

XML logo and Python logo on dark grey background
Encode Strings for XML with Python

Properly format strings for XML with Python.

UFW, Ubuntu, and firewall logos on dark grey background
Allow SMB in UFW

Allow SMB traffic in UFW on Ubuntu & Debian.

JavaScript logo and function text on grey background
Write Self-Executing JavaScript Functions

Make variable maintenance easier with self-executing functions.