简体   繁体   中英

Read files from Cloud Storage having definite prefix but random postfix

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)

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)

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM