Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a bucket exists in GCS with python

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?

like image 312
Student Avatar asked Jan 25 '23 05:01

Student


2 Answers

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)
like image 169
Daniel Wyatt Avatar answered Jan 27 '23 20:01

Daniel Wyatt


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

like image 24
rsalinas Avatar answered Jan 27 '23 18:01

rsalinas