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

8
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是什么。
谢谢。

那么,问题到底是什么? - Doug Stevenson
2个回答

10
您所错过的是,GCS对象在存储桶中并非以类似于文件系统的目录结构/层次结构组织,而是以扁平结构组织。更详细的解释可以在如何工作子目录(在gsutil上下文中,但根本原因相同- GCS扁平名称空间)中找到:

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

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

9
如果您想查找存在于特定前缀(子目录)下的blob(文件),您可以在list_blobs()函数中指定prefixdelimiter参数。请参见以下示例,该示例取自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)

你怎么获取一个文件名,比如1.txt? - FatiHe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接