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

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

    Check out

    bucket.get_key(
        key_name, 
        headers=None, 
        version_id=None, 
        response_headers=None, 
        validate=True
    )
    

    Check to see if a particular key exists within the bucket. This method uses a HEAD request to check for the existence of the key. Returns: An instance of a Key object or None

    from Boto S3 Docs

    You can just call bucket.get_key(keyname) and check if the returned object is None.

提交回复
热议问题