To check if a file exists in an AWS S3 bucket, the easiest way is with a try/except block and using the boto3 get_object() function.
import boto3
s3c = boto3.client('s3', region_name="us-east-2",aws_access_key_id="YOUR AWS_ACCESS_KEY_ID",aws_secret_access_key="YOUR AWS_SECRET_ACCESS_KEY")
try:
obj = s3c.get_object(Bucket="YOUR-BUCKET",Key="FILENAME")
result = obj["Body"].read()
except s3c.exceptions.NoSuchKey:
#File doesn't exist
pass
When working with files in your programs, sometimes you need to be able to easily check if a file exists.
One example of this is if you have your data stored in an AWS S3 bucket and you want to make sure the file exists.
In Python, the boto3 package allows you to easily interact with and create, configure and manage AWS services.
To start, you need to connect to AWS. This is done by first using the boto3 client() function. You should pass your access key and secret access key here to authenticate.
Then, to check if a file exists in the bucket, you should use a try/except block.
Inside the try/except block, you shoud use the boto3 get_object() function. If the function get_object() is able to get the object, there will be no exception and you will be able to continue. If there is an exception, then your program will not error out and you can handle the exception.
Below shows the full code for checking if a particular key exists in an AWS S3 bucket.
import boto3
s3c = boto3.client('s3', region_name="us-east-2",aws_access_key_id="YOUR AWS_ACCESS_KEY_ID",aws_secret_access_key="YOUR AWS_SECRET_ACCESS_KEY")
try:
obj = s3c.get_object(Bucket="YOUR-BUCKET",Key="FILENAME")
result = obj["Body"].read()
except s3c.exceptions.NoSuchKey:
#File doesn't exist
pass
Hopefully this article has been useful for you to learn how to check if a file exists in an AWS S3 bucket using Python.