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

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

    There is one simple way by which we can check if file exists or not in S3 bucket. We donot need to use exception for this

    sesssion = boto3.Session(aws_access_key_id, aws_secret_access_key)
    s3 = session.client('s3')
    
    object_name = 'filename'
    bucket = 'bucketname'
    obj_status = s3.list_objects(Bucket = bucket, Prefix = object_name)
    if obj_status.get('Contents'):
        print("File exists")
    else:
        print("File does not exists")
    

提交回复
热议问题