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

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

提交回复
热议问题