加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python-3.x – 如何使用Python访问存储桶GCS的子文件夹中的文件

发布时间:2020-12-20 11:09:40 所属栏目:Python 来源:网络整理
导读:from google.cloud import storageimport osbucket = client.get_bucket('path to bucket') 上面的代码将我连接到我的桶,但我很难连接到桶中的特定文件夹. 我正在尝试此代码的变体,但没有运气: blob = bucket.get_blob("training/bad")blob = bucket.get_bl
from google.cloud import storage
import os
bucket = client.get_bucket('path to bucket')

上面的代码将我连接到我的桶,但我很难连接到桶中的特定文件夹.

我正在尝试此代码的变体,但没有运气:

blob = bucket.get_blob("training/bad")
blob = bucket.get_blob("/training/bad")
blob = bucket.get_blob("path to bucket/training/bad")

我希望能够访问坏子文件夹中的图像列表,但我似乎无法这样做.
尽管阅读了文档,我甚至都不完全理解blob是什么,而是基于教程来实现它.

谢谢.

解决方法

如果要查找特定前缀(子目录)下存在的blob(文件),可以为 list_blobs()函数指定前缀和分隔符参数

请参阅以下来自Google Listing Objects example(也是GitHub snippet)的示例

def list_blobs_with_prefix(bucket_name,prefix,delimiter=None):
    """Lists all the blobs in the bucket that begin with the prefix.

    This can be used to list all blobs in a "folder",e.g. "public/".

    The delimiter argument can be used to restrict the results to only the
    "files" in the given "folder". Without the delimiter,the entire tree under
    the prefix is returned. For example,given these blobs:

        /a/1.txt
        /a/b/2.txt

    If you just specify prefix = '/a',you'll get back:

        /a/1.txt
        /a/b/2.txt

    However,if you specify prefix='/a' and delimiter='/',you'll get back:

        /a/1.txt

    """
    storage_client = storage.Client()
    bucket = storage_client.get_bucket(bucket_name)

    blobs = bucket.list_blobs(prefix=prefix,delimiter=delimiter)

    print('Blobs:')
    for blob in blobs:
        print(blob.name)

    if delimiter:
        print('Prefixes:')
        for prefix in blobs.prefixes:
            print(prefix)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读