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

Moo*_*dra 4 python-3.x google-cloud-storage google-cloud-platform

from google.cloud import storage
import os
bucket = client.get_bucket('path to bucket')
Run Code Online (Sandbox Code Playgroud)

上面的代码将我连接到存储桶,但是我正在努力连接存储桶中的特定文件夹。

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

blob = bucket.get_blob("training/bad")
blob = bucket.get_blob("/training/bad")
blob = bucket.get_blob("path to bucket/training/bad")
Run Code Online (Sandbox Code Playgroud)

我希望能够访问不良子文件夹中的图像列表,但似乎无法这样做。尽管阅读了文档,但我什至不完全了解blob是什么,并且根据教程对其进行了介绍。

谢谢。

Sco*_*McC 7

如果你想找到的斑点特定下存在(文件)的前缀(子目录),你可以指定prefixdelimiter参数的list_blobs()函数

请参阅以下来自 Google Listing Objects 示例(也是GitHub 代码段)的示例

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)
Run Code Online (Sandbox Code Playgroud)


Dan*_*scu 5

您错过的事实是,在GCS中,存储桶中的对象不是以类似于文件系统的目录结构/层次结构组织的,而是以平面结构组织的。

可以在子目录的工作方式中找到更详细的说明(在gsutil上下文中,是的,但是,根本原因是相同的-GCS平面名称空间):

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

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