Checking if file exists in Google Cloud Storage using Python
Start your free 7-days trial now!
To follow along with this guide, please make sure to have:
created a service account and downloaded the private key (JSON file) for authentication (please check out my detailed guide)
installed the Python client library for Google Cloud Storage:pip install --upgrade google-cloud-storage
Checking if a file exists on Google Cloud Storage
To check if a file exists in Google Cloud Storage using Python, use the
Blob.exists() method which returns a
from google.cloud import storage# Authenticate ourselves using the private key of our service accountpath_to_private_key = './gcs-project-354207-099ef6796af6.json'client = storage.Client.from_service_account_json(json_credentials_path=path_to_private_key)bucket = storage.Bucket(client, 'example-bucket-skytowner')blob = bucket.blob('cat.png')blob.exists()True
Here, note the following:
gcs-project-354207-099ef6796af6.jsonis the name of the credential JSON file for the service account. This file is located in the same directory as this Python script.
we are checking whether the file
cat.pngexists - and yes, it does!