check if a key exists in a bucket in s3 using boto3

前端 未结 24 2804
花落未央
花落未央 2020-11-28 19:03

I would like to know if a key exists in boto3. I can loop the bucket contents and check the key if it matches.

But that seems longer and an overkill. Boto3 official

相关标签:
24条回答
  • 2020-11-28 19:31

    In Boto3, if you're checking for either a folder (prefix) or a file using list_objects. You can use the existence of 'Contents' in the response dict as a check for whether the object exists. It's another way to avoid the try/except catches as @EvilPuppetMaster suggests

    import boto3
    client = boto3.client('s3')
    results = client.list_objects(Bucket='my-bucket', Prefix='dootdoot.jpg')
    return 'Contents' in results
    
    0 讨论(0)
  • 2020-11-28 19:31

    This could check both prefix and key, and fetches at most 1 key.

    def prefix_exits(bucket, prefix):
        s3_client = boto3.client('s3')
        res = s3_client.list_objects_v2(Bucket=bucket, Prefix=prefix, MaxKeys=1)
        return 'Contents' in res
    
    0 讨论(0)
  • 2020-11-28 19:31

    It's really simple with get() method

    import botocore
    from boto3.session import Session
    session = Session(aws_access_key_id='AWS_ACCESS_KEY',
                    aws_secret_access_key='AWS_SECRET_ACCESS_KEY')
    s3 = session.resource('s3')
    bucket_s3 = s3.Bucket('bucket_name')
    
    def not_exist(file_key):
        try:
            file_details = bucket_s3.Object(file_key).get()
            # print(file_details) # This line prints the file details
            return False
        except botocore.exceptions.ClientError as e:
            if e.response['Error']['Code'] == "NoSuchKey": # or you can check with e.reponse['HTTPStatusCode'] == '404'
                return True
            return False # For any other error it's hard to determine whether it exists or not. so based on the requirement feel free to change it to True/ False / raise Exception
    
    print(not_exist('hello_world.txt')) 
    
    0 讨论(0)
  • 2020-11-28 19:32

    The easiest way I found (and probably the most efficient) is this:

    import boto3
    from botocore.errorfactory import ClientError
    
    s3 = boto3.client('s3')
    try:
        s3.head_object(Bucket='bucket_name', Key='file_path')
    except ClientError:
        # Not found
        pass
    
    0 讨论(0)
  • 2020-11-28 19:32

    you can use Boto3 for this.

    import boto3
    s3 = boto3.resource('s3')
    bucket = s3.Bucket('my-bucket')
    objs = list(bucket.objects.filter(Prefix=key))
    if(len(objs)>0):
        print("key exists!!")
    else:
        print("key doesn't exist!")
    

    Here key is the path you want to check exists or not

    0 讨论(0)
  • 2020-11-28 19:32

    Here is a solution that works for me. One caveat is that I know the exact format of the key ahead of time, so I am only listing the single file

    import boto3
    
    # The s3 base class to interact with S3
    class S3(object):
      def __init__(self):
        self.s3_client = boto3.client('s3')
    
      def check_if_object_exists(self, s3_bucket, s3_key):
        response = self.s3_client.list_objects(
          Bucket = s3_bucket,
          Prefix = s3_key
          )
        if 'ETag' in str(response):
          return True
        else:
          return False
    
    if __name__ == '__main__':
      s3  = S3()
      if s3.check_if_object_exists(bucket, key):
        print "Found S3 object."
      else:
        print "No object found."
    
    0 讨论(0)
提交回复
热议问题