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

如何为Python从Google Cloud Storage下载目录添加进度条

给GCS目录下载添加进度条

首先安装常用的进度条工具库 tqdm:

pip install tqdm

接下来修改你的代码,通过以下步骤实现进度条功能:

  1. 导入tqdm模块
  2. 提前统计待下载文件的总大小(或文件数量),让进度条能展示整体进度
  3. 在下载循环中用tqdm更新进度

修改后的完整代码

from google.cloud import storage
from pathlib import Path
from tqdm import tqdm

def download_blob():
    """Downloads a blob from the bucket."""
    # The ID of your GCS bucket
    bucket_name = "Bucket name"

    # The ID of your GCS object
    blob_name = input(f"Enter the folder name in {bucket_name} : ")

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)
    # 先将blob列表转为可迭代对象,方便过滤和统计
    blobs = list(bucket.list_blobs(prefix=blob_name))
    # 过滤掉目录类型的blob(末尾带/的)
    file_blobs = [blob for blob in blobs if not blob.name.endswith("/")]
    
    if not file_blobs:
        print("指定文件夹下没有可下载的文件")
        return

    # 统计所有待下载文件的总字节数
    total_size = sum(blob.size for blob in file_blobs)
    print('开始下载文件')
    
    # 初始化进度条:总大小为字节数,自动缩放单位(KB/MB等)
    with tqdm(total=total_size, unit='B', unit_scale=True, desc='下载进度') as pbar:
        for blob in file_blobs:
            # 创建本地目录
            file_split = blob.name.split("/")
            directory = "/".join(file_split[0:-1])
            Path(directory).mkdir(parents=True, exist_ok=True)
            # 下载文件
            blob.download_to_filename(blob.name)
            # 更新进度条(加上当前文件的大小)
            pbar.update(blob.size)
    
    print('下载完成')

download_blob()

可选:按文件数量显示进度

如果不需要按字节统计,只想按下载的文件个数展示进度,可以替换进度相关的代码段:

# 统计待下载文件总数
total_files = len(file_blobs)
print('开始下载文件')

# 初始化进度条:按文件数量计数
with tqdm(total=total_files, unit='个', desc='下载进度') as pbar:
    for blob in file_blobs:
        # 目录创建和下载代码不变
        file_split = blob.name.split("/")
        directory = "/".join(file_split[0:-1])
        Path(directory).mkdir(parents=True, exist_ok=True)
        blob.download_to_filename(blob.name)
        # 每下载完一个文件,进度+1
        pbar.update(1)

内容的提问来源于stack exchange,提问作者Theophin Johnson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:15:54