【问题标题】:Google Cloud Storage : Python API get blob information with wildcard谷歌云存储:Python API 使用通配符获取 blob 信息
【发布时间】:2019-07-18 02:34:23
【问题描述】:

我正在尝试从存储桶中获取 blob 信息,但我想在 blob 名称中使用通配符。考虑一下我的桶

$ gsutil ls gs://myBucket/myPath/
gs://myBucket/myPath/
gs://myBucket/myPath/ranOn=2018-12-11/
gs://myBucket/myPath/ranOn=2018-12-12/
gs://myBucket/myPath/ranOn=2018-12-13/
gs://myBucket/myPath/ranOn=2018-12-14/
gs://myBucket/myPath/ranOn=2018-12-15/
gs://myBucket/myPath/ranOn=2019-02-18/
gs://myBucket/myPath/ranOn=2019-02-19/
gs://myBucket/myPath/ranOn=2019-02-20/
gs://myBucket/myPath/ranOn=2019-02-21/

现在从命令行,我可以做

$ gsutil ls gs://myBucket/myPath/ranOn=2018*
gs://myBucket/myPath/
gs://myBucket/myPath/ranOn=2018-12-11/
gs://myBucket/myPath/ranOn=2018-12-12/
gs://myBucket/myPath/ranOn=2018-12-13/
gs://myBucket/myPath/ranOn=2018-12-14/
gs://myBucket/myPath/ranOn=2018-12-15/

因此我可以对尺寸做同样的事情

$ gsutil du -sh gs://myBucket/myPath/ranOn=2018*
2.7 G

现在,我想用 python api 做同样的事情。这是我尝试过的

from google.cloud import storage

storage_client = storage.Client()
bucket = storage_client.get_bucket('myBucket')
blob = bucket.get_blob('myPath/ranOn=2018*')
print('Size: {} bytes'.format(blob.size))
Size: None bytes

为什么这不起作用?如何通过 python api 在 blob 路径中使用通配符?

【问题讨论】:

  • gsutil 在其添加到 Cloud Storage 上方的代码中实现了通配符。 Cloud Storage API 不支持此功能。你需要在你的代码中做同样的事情。

标签: python google-cloud-platform google-cloud-storage


【解决方案1】:

不幸的是,get_blob 仅用于获取单个文件,而不是多个文件。

您需要遍历与前缀匹配的所有文件并将它们的大小相加以获得总大小。

blobs = bucket.list_blobs(prefix="myPath/ranOn=2018")

total = sum([blob.size for blob in blobs])

【讨论】:

    猜你喜欢
    • 2020-01-15
    • 1970-01-01
    • 2018-11-25
    • 2012-03-02
    • 2018-07-08
    • 2023-03-12
    • 1970-01-01
    • 2021-04-14
    • 1970-01-01
    相关资源
    最近更新 更多