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

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

    import boto3
    client = boto3.client('s3')
    s3_key = 'Your file without bucket name e.g. abc/bcd.txt'
    bucket = 'your bucket name'
    content = client.head_object(Bucket=bucket,Key=s3_key)
        if content.get('ResponseMetadata',None) is not None:
            print "File exists - s3://%s/%s " %(bucket,s3_key) 
        else:
            print "File does not exist - s3://%s/%s " %(bucket,s3_key)
    

提交回复
热议问题