How can I easily determine if a Boto 3 S3 bucket resource exists?

后端 未结 6 1565
滥情空心
滥情空心 2020-12-29 01:34

For example, I have this code:

import boto3

s3 = boto3.resource(\'s3\')

bucket = s3.Bucket(\'my-bucket-name\')

# Does it exist???
6条回答
  •  Happy的楠姐
    2020-12-29 01:55

    As mentioned by @Daniel, the best way as suggested by Boto3 docs is to use head_bucket()

    head_bucket() - This operation is useful to determine if a bucket exists and you have permission to access it.

    If you have a small number of buckets, you can use the following:

    >>> import boto3
    >>> s3 = boto3.resource('s3')
    >>> s3.Bucket('Hello') in s3.buckets.all()
    False
    >>> s3.Bucket('some-docs') in s3.buckets.all()
    True
    >>> 
    

提交回复
热议问题