从 Cloud Storage 读取具有确定前缀但随机后缀的文件

Tee*_*Kay 1 file python-3.x google-cloud-storage google-cloud-platform google-cloud-functions

我使用以下代码从 Cloud Functions 读取 Google Cloud Storage 中的文件内容。这里定义了文件名(filename)。我现在的文件有明确的前缀,但后缀可以是任何东西。示例 - ABC-khasvbdjfy7i76.csv

如何读取此类文件的内容?

我知道会有“ABC”作为前缀。但后缀可以是任意的。

storage_client = storage.Client()
bucket = storage_client.get_bucket('test-bucket')
blob = bucket.blob(filename)
contents = blob.download_as_string()
print("Contents : ")
print(contents)
Run Code Online (Sandbox Code Playgroud)

nor*_*bjd 6

您可以使用方法prefix的参数list_blobs来过滤以前缀开头的对象,并迭代对象:

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)
Run Code Online (Sandbox Code Playgroud)