这种方法可以使用方法的prefixanddelimiter参数来完成list_blobs。
例如,如果要列出文件夹中root但不在文件夹中的所有对象,可以使用以下代码段:
from google.cloud import storage
client = storage.Client()
bucket = client.get_bucket("my_bucket")
all_blobs = list(client.list_blobs(bucket, prefix="", delimiter="/"))
for blob in all_blobs:
print (blob.name)
另外,请注意,在列出时root不需要添加prefix参数:
from google.cloud import storage
client = storage.Client()
bucket = client.get_bucket("my_bucket")
all_blobs = list(client.list_blobs(bucket, delimiter="/"))
for blob in all_blobs:
print (blob.name)
例如,另一种方法可以是列出文件夹内的文件,但不递归地列出,即该文件夹根目录中的对象。那么代码可能是:
from google.cloud import storage
client = storage.Client()
bucket = client.get_bucket("my_bucket")
all_blobs = list(client.list_blobs(bucket,prefix="folder/", delimiter="/"))
for blob in all_blobs:
print (blob.name)
您可以prefix根据列出时使用的路径更改。
如果您可能想要列出除特定文件夹之外的所有内容,则没有直接的方法可以使用 Cloud Storage 库来做到这一点。在这种情况下,我认为最好的方法是在客户端过滤数据。您可以使用正则表达式过滤您在 Storage 中列出后得到的列表:
from google.cloud import storage
import re
regex = re.compile(r'folder.*')
client = storage.Client()
bucket = client.get_bucket("my_bucket")
all_blobs = list(client.list_blobs(bucket))
filtered = [blob for blob in all_blobs if not regex.match(blob.name)]
for blob in filtered:
print(blob.name)