You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python列出Firebase Cloud Storage指定子目录的文件与文件夹?

使用pyrebase4列出Firebase Cloud Storage指定目录内容

1. 所需导入库

import pyrebase

2. Firebase应用初始化

将你的serviceAccount密钥文件(如serviceAccount.json)放在项目目录下,初始化代码如下:

config = {
    "apiKey": "你的API_KEY",
    "authDomain": "你的项目ID.firebaseapp.com",
    "projectId": "你的项目ID",
    "storageBucket": "你的项目ID.appspot.com",
    "serviceAccount": "serviceAccount.json",  # 本地密钥文件路径
    "messagingSenderId": "你的Sender ID",
    "appId": "你的App ID"
}

firebase = pyrebase.initialize_app(config)
storage = firebase.storage()

3. 获取指定目录的文件和文件夹

方法1:使用pyrebase4原生list_files方法

通过prefix指定目标目录,搭配delimiter="/"区分文件与虚拟文件夹:

def list_dir_contents(storage, target_prefix):
    # 确保前缀以斜杠结尾,精准匹配目录
    if not target_prefix.endswith("/"):
        target_prefix += "/"
    
    # 获取指定前缀下的所有条目
    entries = storage.list_files(prefix=target_prefix, delimiter="/")
    
    files = []
    dirs = []
    for entry in entries:
        # 跳过目录本身的前缀条目
        if entry.name == target_prefix:
            continue
        if entry.name.endswith("/"):
            dirs.append(entry.name)
        else:
            files.append(entry.name)
    
    return files, dirs

# 调用示例
files, dirs = list_dir_contents(storage, "images/")
print("文件列表:", files)
print("文件夹列表:", dirs)

方法2:直接调用Google Cloud Storage原生API

如果list_files仍有问题,可直接操作底层Bucket对象:

# 获取Bucket实例
bucket = storage.bucket()

# 列出指定前缀下的文件与虚拟文件夹
blobs = bucket.list_blobs(prefix="files/", delimiter="/")

# 提取文件列表
file_list = [blob.name for blob in blobs]
# 提取虚拟文件夹列表
dir_list = list(blobs.prefixes)

print("文件列表:", file_list)
print("文件夹列表:", dir_list)

遍历全部1万条文件的成本与效率分析

  • 时间成本:遍历1万条文件需要多次分页请求(默认每页返回1000条),每次请求存在网络延迟,整体耗时远高于前缀过滤的精准请求,网络环境一般时延迟会更明显。
  • 费用成本:Firebase Storage的列表操作按请求次数和返回对象数量计费。遍历1万条至少产生10次请求,而前缀过滤仅需1-2次请求,长期频繁操作会积累更多不必要的费用。
  • 效率对比:前缀过滤是最优方案,避免了冗余的数据传输和请求,远优于全量遍历后再判断的方式。

内容的提问来源于stack exchange,提问作者Homit Dalia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 20:43:27