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

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

提交回复
热议问题