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

前端 未结 24 2910
花落未央
花落未央 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:35

    For boto3, ObjectSummary can be used to check if an object exists.

    Contains the summary of an object stored in an Amazon S3 bucket. This object doesn't contain contain the object's full metadata or any of its contents

    import boto3
    from botocore.errorfactory import ClientError
    def path_exists(path, bucket_name):
        """Check to see if an object exists on S3"""
        s3 = boto3.resource('s3')
        try:
            s3.ObjectSummary(bucket_name=bucket_name, key=path).load()
        except ClientError as e:
            if e.response['Error']['Code'] == "404":
                return False
            else:
                raise e
        return True
    
    path_exists('path/to/file.html')
    

    In ObjectSummary.load

    Calls s3.Client.head_object to update the attributes of the ObjectSummary resource.

    This shows that you can use ObjectSummary instead of Object if you are planning on not using get(). The load() function does not retrieve the object it only obtains the summary.

提交回复
热议问题