Skip to content

Instantly share code, notes, and snippets.

@crabba
Last active November 10, 2021 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crabba/256278efc17cd19e2cb772b5cf01fe7d to your computer and use it in GitHub Desktop.
Save crabba/256278efc17cd19e2cb772b5cf01fe7d to your computer and use it in GitHub Desktop.
S3 test if an object exists
#! /usr/bin/env python3
import boto3
import sys
s3client = boto3.client('s3')
def s3_object_exists(bucket, key):
ret = False
try:
metadata = s3client.head_object(Bucket=bucket, Key=key)
ret = True
except s3client.exceptions.NoSuchKey as e:
print(f"nosuchkey: {e}")
pass
except s3client.exceptions.NoSuchBucket as e:
print(f"nosuchbucket: {e}")
pass
except Exception as e:
print(f"Exception {type(e).__name__}: {e}")
return ret
(bucket, key) = sys.argv[1:3]
ret = s3_object_exists(bucket, key)
print(f"{ret}: {bucket}, {key}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment