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

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

    S3_REGION="eu-central-1"
    bucket="mybucket1"
    name="objectname"
    
    import boto3
    from botocore.client import Config
    client = boto3.client('s3',region_name=S3_REGION,config=Config(signature_version='s3v4'))
    list = client.list_objects_v2(Bucket=bucket,Prefix=name)
    for obj in list.get('Contents', []):
        if obj['Key'] == name: return True
    return False
    

提交回复
热议问题