I have a script where I want to check if a file exists in a bucket and if it doesn't then create one.
I tried using os.path.exists(file_path)
where file_path = "/gs/testbucket"
, but I got a file not found error.
I know that I can use the files.listdir()
API function to list all the files located at a path and then check if the file I want is one of them. But I was wondering whether there is another way to check whether the file exists.
This post is old, you can actually now check if a file exists on GCP using the blob class, but because it took me a while to find an answer, adding here for the others who are looking for a solution
from google.cloud import storage
name = 'file_i_want_to_check.txt'
storage_client = storage.Client()
bucket_name = 'my_bucket_name'
bucket = storage_client.bucket(bucket_name)
stats = storage.Blob(bucket=bucket, name=name).exists(storage_client)
Documentation is here
Hope this helps!