如何在我的 GCP 存储桶对象路径中使用通配符?

发布于 2025-01-14 16:07:00 字数 498 浏览 3 评论 0原文

我的主要问题是, 我想检查 gcp 中的对象是否存在。所以,我所尝试的

from google.cloud import storage
client = storage.Client()
path_exists = False
for blob in client.list_blobs('models', prefix='trainedModels/mddeep256_sarim'):
    path_exists = True
    break

对我来说效果很好。 但现在的问题是我不知道模型名称 mddeep256 但我知道更多部分 _sarim

所以,我想使用像

for blob in client.list_blobs('models', prefix='trainedModels/*_sarim'):

我想使用 * 通配符 这样的东西,我该怎么做?

My main problem is,
I want to check if an object in gcp exists or not. So, what I tried

from google.cloud import storage
client = storage.Client()
path_exists = False
for blob in client.list_blobs('models', prefix='trainedModels/mddeep256_sarim'):
    path_exists = True
    break

It worked fine for me.
But now the problem is I don't know the model name which is mddeep256 but I know further part _sarim

So, I want to use something like

for blob in client.list_blobs('models', prefix='trainedModels/*_sarim'):

I want to use * wildcard, how can I do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

伴我老 2025-01-21 16:07:00

list_blob 不支持 prefix 中的正则表达式。正如吉洛姆提到的,你需要自己过滤。

以下应该有效。

def is_object_exist(bucket_name, object_pattern):
    from google.cloud import storage
    import re
    client = storage.Client()
    all_blobs = client.list_blobs(bucket_name)
    regex = re.compile(r'{}'.format(object_pattern))
    filtered_blobs = [b for b in all_blobs if regex.match(b.name)]
    return True if len(filtered_blobs) else False

list_blob doesn't support regex in prefix. you need filter by yourself as mentioned by Guilaume.

following should work.

def is_object_exist(bucket_name, object_pattern):
    from google.cloud import storage
    import re
    client = storage.Client()
    all_blobs = client.list_blobs(bucket_name)
    regex = re.compile(r'{}'.format(object_pattern))
    filtered_blobs = [b for b in all_blobs if regex.match(b.name)]
    return True if len(filtered_blobs) else False
怪我闹别瞎闹 2025-01-21 16:07:00

简而言之:你不能!

您只能过滤前缀。如果您想过滤后缀(如您所愿),请首先过滤 API 可以实现的最长前缀,然后在代码中迭代以扫描文件名并获取与您的模式匹配的文件名。

没有内置的解决方案......

In short: you can't!

You can only filter on the prefix. If you want to filter on the suffix (as you wish), start by filter on the longest prefix that you can with the API, and then iterate in your code to scan the file name and get those that match your pattern.

No built-il solution for that...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文