如何使用Python访问存储桶GCS的子文件夹中的文件?

问题描述 投票:4回答:2
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是什么,而是基于教程来实现它。

谢谢。

python-3.x google-cloud-platform google-cloud-storage
2个回答
2
投票

如果您想查找特定前缀(子目录)下存在的blob(文件),您可以为prefix函数指定delimiterlist_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)

5
投票

你错过的是,在一个桶中的GCS对象不是在类似文件系统的目录结构/层次结构中组织的,而是在一个扁平结构中。

更详细的解释可以在How Subdirectories Work中找到(在gsutil上下文中,为true,但基本原因是相同的 - GCS flat命名空间):

gsutil提供了Google云端存储服务支持的“平面”名称空间顶部的分层文件树的错觉。对于服务,对象gs://your-bucket/abc/def.txt只是一个恰好在其名称中包含“/”字符的对象。没有“abc”目录;只是一个具有给定名称的对象。

由于GCS中没有(子)目录,因此/training/bad实际上并不存在,因此您无法列出其内容。您所能做的就是列出存储桶中的所有对象,并选择名称/路径以/training/bad开头的对象。

© www.soinside.com 2019 - 2024. All rights reserved.