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

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

    Assuming you just want to check if a key exists (instead of quietly over-writing it), do this check first:

    import boto3
    
    def key_exists(mykey, mybucket):
      s3_client = boto3.client('s3')
      response = s3_client.list_objects_v2(Bucket=mybucket, Prefix=mykey)
      if response:
          for obj in response['Contents']:
              if mykey == obj['Key']:
                  return True
      return False
    
    if key_exists('someprefix/myfile-abc123', 'my-bucket-name'):
        print("key exists")
    else:
        print("safe to put new bucket object")
        # try:
        #     resp = s3_client.put_object(Body="Your string or file-like object",
        #                                 Bucket=mybucket,Key=mykey)
        # ...check resp success and ClientError exception for errors...
    

提交回复
热议问题