8

Code:

from google.cloud import storage

client = storage.Client()

bucket = ['symbol_wise_nse', 'symbol_wise_final']

for i in bucket:
    if client.get_bucket(i).exists():
        BUCKET = client.get_bucket(i)

if the bucket exists i want to do client.get_bucket. How to check whether the bucket exists or not?

1
  • It seems you have code that is checking for this already. I’m assuming it’s not working as expected. Are you getting an error message? Is the condition never being triggered? Or is this intended as pseudo code which does not compile? Mar 19, 2020 at 9:12

4 Answers 4

10

Another option that doesn't use try: except is:

from google.cloud import storage

client = storage.Client()    

bucket = ['symbol_wise_nse', 'symbol_wise_final']
for i in bucket:
    BUCKET = client.bucket(i)
    if BUCKET.exists():
        BUCKET = client.get_bucket(i)
2

There is no method to check if the bucket exists or not, however you will get an error if you try to access a non existent bucket.

I would recommend you to either list the buckets in the project with storage_client.list_buckets() and then use the response to confirm if the bucket exists in your code, or if you wish to perform the client.get_bucket in every bucket in your project, you can just iterate through the response directly.

Hope you find this information useful

1
1

You can use something like this:

from google.cloud import storage

client = storage.Client()

buckets = ['symbol_wise_nse', 'symbol_wise_final']

for i in buckets:
  try:
       bucket = client.get_bucket(i)
       print(bucket)
  except:
       pass

1

The following worked for me (re-using params in question):

from google.cloud import storage
from google.cloud.storage import Bucket

client = storage.Client()
exists = Bucket(client, 'symbol_wise_nse').exists()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.