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

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

    If you have less than 1000 in a directory or bucket you can get set of them and after check if such key in this set:

    files_in_dir = {d['Key'].split('/')[-1] for d in s3_client.list_objects_v2(
    Bucket='mybucket',
    Prefix='my/dir').get('Contents') or []}
    

    Such code works even if my/dir is not exists.

    http://boto3.readthedocs.io/en/latest/reference/services/s3.html#S3.Client.list_objects_v2

提交回复
热议问题