boto3 file_upload does it check if file exists
You can test the existence of an object using s3_client.head_object()
or s3_service.Object().load()
:
import boto3
from botocore.exceptions import ClientError
def check(s3_client, bucket, key):
try:
s3_client.head_object(Bucket=bucket, Key=key)
except ClientError as e:
return int(e.response['Error']['Code']) != 404
return True
s3_client = boto3.client('s3')
print(check(s3_client, <bucket>, <key>))
With s3
service resource this would achieve the same:
def check(s3_service, bucket, key):
try:
s3_service.Object(bucket, key).load()
except ClientError as e:
return int(e.response['Error']['Code']) != 404
return True
s3_service = boto3.resource(service_name='s3')
print(check(s3_service, <bucket>, <key>))
You can use this code
import boto3
s3 = boto3.resource('s3')
bucket = s3.Bucket('my-bucket')
key = 'dootdoot.jpg'
objs = list(bucket.objects.filter(Prefix=key))
if len(objs) > 0 and objs[0].key == key:
print("Exists!")
else:
print("Doesn't exist")