【问题标题】:Read files from Cloud Storage having definite prefix but random postfix从具有明确前缀但随机后缀的 Cloud Storage 读取文件
【发布时间】:2019-10-10 01:20:06
【问题描述】:

我正在使用以下代码从 Cloud Functions 读取 Google Cloud Storage 中的文件内容。这里定义了文件名(文件名)。我现在的文件有明确的前缀,但后缀可以是任何东西。 示例 - 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)

【问题讨论】:

    标签: python-3.x file google-cloud-platform google-cloud-functions google-cloud-storage


    【解决方案1】:

    您需要知道文件的完整路径才能读取它。而且由于客户端无法猜测随机后缀,因此您首先必须列出所有带有非随机前缀的文件。

    有一个list 操作,您可以向其传递前缀,如下所示:Google Cloud Storage + Python : Any way to list obj in certain folder in GCS?

    【讨论】:

      【解决方案2】:

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

      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)
      

      【讨论】:

        猜你喜欢
        • 2012-10-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-29
        • 1970-01-01
        • 1970-01-01
        • 2021-05-10
        相关资源
        最近更新 更多