Google Cloud Storage 列出具有特定文件名的 Blob 对象

问题描述 投票:0回答:6

在 google.cloud.storage 和 list_blobs 的帮助下,我可以从特定存储桶中获取文件列表。但我想从存储桶中过滤(名称*.ext)确切的文件。我无法找到确切的解决方案。

例如:buket=data,prefix_folder_name=sales,在前缀文件夹中,我有带有元数据的发票列表。我想获取特定的发票及其元数据(name*.csv & name.*.meta)。另外,如果我循环特定文件夹的整个 all_blob 来获取所选文件,那么这将是大量数据,并且可能会影响性能。

如果有人帮助我解决这个问题,那就太好了。

bucket = gcs_client.get_bucket(buket)
all_blobs = bucket.list_blobs(prefix=prefix_folder_name)
for blob in all_blobs: 
  print(blob.name)
python google-cloud-storage client-library
6个回答
5
投票

根据 google-cloud-storage 文档 Blob 是具有

name
属性的对象,因此您可以通过此属性过滤它们。

from google.cloud import storage

# storage_client = gcs client
storage_client = storage.Client()

# bucket_name = "your-bucket-name"
# Note: Client.list_blobs requires at least package version 1.17.0.
blobs = storage_client.list_blobs(bucket_name)

# filter_dir = "filter-string"
[blob.name for blob in blobs if filter_dir in blob.name ]

2
投票

它不允许你过滤,但你可以使用 fields 参数只返回对象的名称,限制返回的数据量并方便过滤。


2
投票

您可以使用 match_glob 参数来做到这一点,例如

bucket.list_blobs(match_glob='*.ext')

1
投票

您可以过滤前缀,但要更具体地过滤(例如,以给定名称扩展名结尾的对象),您必须实现客户端过滤逻辑。这就是当您执行如下命令时

gsutil
所做的事情:

gsutil ls gs://your-bucket/abc*.txt

0
投票

您可以使用以下内容,将文件的过滤器视为

name
.ext

all_blobs = bucket.list_blobs()    
fileList = [file.name for file in all_blobs if '.ext' in file.name and 'name' in file.name]

for file in fileList: 
  print(file)

这里

name
将是文件名过滤器,
.ext
将是您的扩展过滤器。


0
投票

扩展@michael-vehrs的答案,如果您需要查看所有目录级别,请务必在前面添加

**/

from google.cloud import storage
bucket = storage.Client().bucket("bucket-name")
bucket.list_blobs(match_glob="**/*.ext")
© www.soinside.com 2019 - 2024. All rights reserved.