0

I am using the following code to read the contents of a file in Google Cloud Storage from Cloud Functions. Here the name of file (filename) is defined. I now have files that will have a definite prefix but the postfix can be anything. Example - ABC-khasvbdjfy7i76.csv

How to read the contents of such files?

I know there will be "ABC" as a prefix. But the postfix can be anything random.

storage_client = storage.Client()
bucket = storage_client.get_bucket('test-bucket')
blob = bucket.blob(filename)
contents = blob.download_as_string()
print("Contents : ")
print(contents)
TeeKay
  • 1,025
  • 2
  • 22
  • 60

2 Answers2

5

You can use prefix parameter of list_blobs method to filter objects beginning with your prefix, and iterate on the objects :

from google.cloud import storage

storage_client = storage.Client()
bucket = storage_client.get_bucket('test-bucket')

blobs = bucket.list_blobs(prefix="ABC")

for blob in blobs:
    contents = blob.download_as_string()
    print("Contents of %s:" % blob.name)
    print(contents)
norbjd
  • 10,166
  • 4
  • 45
  • 80
0

You need to know the entire path of a file to be able to read it. And since the client can't guess the random suffix, you will first have to list all the files with the non-random prefix.

There is a list operation, to which you can pass a prefix, as shown here: Google Cloud Storage + Python : Any way to list obj in certain folder in GCS?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807