如何在GCS中使用Python获取子文件夹中没有路由的文件名?

2024-04-26 17:36:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个有很多子文件夹的bucket,我用这个函数来获取blob,但是我需要获取文件名,怎么做呢?你知道吗

def list_blobs_with_prefix(bucket_name, prefix,delimiter=None):
    storage_client = storage.Client()
    blobs = storage_client.list_blobs(bucket_name, prefix=prefix,delimiter=delimiter)
    return blobs

我需要获得没有文件夹路由的文件名,在另一个函数中使用它,该函数尝试下载文件并将其放入临时文件夹。你知道吗


Tags: 函数name文件夹clientnoneprefixbucket文件名
1条回答
网友
1楼 · 发布于 2024-04-26 17:36:12

此脚本将为您提供一个列表,其中只包含bucket中的文件名,而不包含文件夹/子文件夹/路由

from google.cloud import storage


client = storage.Client()
BUCKET_NAME = 'thehotbucket'
bucket = client.get_bucket(BUCKET_NAME)

blobs = bucket.list_blobs()

for blob in blobs:
    try:
        num = blob.name.count('/')
        string = blob.name.split('/')[num]
        if string != "":
            print(string)
    except:
        print("An exception occurred")

相关问题 更多 >