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

Colab中向Google Drive下载大文件如何实现断点续传?

Colab 超大文件Google Drive断点续传实现方案

要实现断点续传,核心是利用HTTP协议的Range请求头,让服务器从本地已下载的文件位置继续传输数据,同时本地文件以追加模式写入,避免覆盖已下载内容。以下是针对你现有代码的修改方案:

核心逻辑说明

  1. 挂载Drive:Colab环境下需先将Google Drive挂载到文件系统,才能直接写入文件到Drive
  2. 检查本地文件状态:如果目标文件已存在,读取已下载的字节数
  3. 发送续传请求:通过Range请求头告知服务器从指定位置开始传输
  4. 处理响应:服务器支持续传则返回206状态码,此时追加写入文件;不支持则从头下载
  5. 进度条适配:进度计算从已下载的字节数开始,避免重复统计

修改后的完整代码

from requests import get
import sys
import os
from google.colab import drive

# 挂载Google Drive,首次运行需授权
drive.mount('/content/drive')

def download(url, file_name):
    # 检查文件是否存在,获取已下载大小
    downloaded_size = 0
    if os.path.exists(file_name):
        downloaded_size = os.path.getsize(file_name)
        print(f"已下载 {downloaded_size} 字节,开始续传...")

    # 构造Range请求头,指定续传起始位置
    headers = {}
    if downloaded_size > 0:
        headers['Range'] = f'bytes={downloaded_size}-'

    # 发送请求
    response = get(url, stream=True, headers=headers)

    # 处理响应状态码
    if response.status_code == 206:
        # 服务器支持续传,以追加模式打开文件
        mode = 'ab'
        total_length = int(response.headers.get('content-length')) + downloaded_size
    elif response.status_code == 200:
        # 服务器不支持续传,从头下载并覆盖文件
        mode = 'wb'
        total_length = int(response.headers.get('content-length'))
        downloaded_size = 0
        print("服务器不支持断点续传,将从头开始下载")
    else:
        print(f"请求失败,状态码:{response.status_code}")
        return

    print(f"开始下载/续传 {file_name},总大小:{total_length} 字节")

    with open(file_name, mode) as f:
        dl = downloaded_size
        for data in response.iter_content(chunk_size=4096):
            dl += len(data)
            f.write(data)
            # 更新进度条
            done = int(50 * dl / total_length)
            sys.stdout.write("\r[%s%s] %d%%" % ('=' * done, ' ' * (50 - done), int(100 * dl / total_length)))
            sys.stdout.flush()
    print("\n下载/续传完成!")

# 使用示例:替换为你的下载链接和Drive目标路径
download("https://example.com/large-file.iso", "/content/drive/MyDrive/MyFiles/large-file.iso")

注意事项

  • 服务器兼容性:大部分正规文件服务器支持Range请求,若返回416状态码,说明已下载大小超过文件总大小,可删除本地文件重新下载
  • Colab会话问题:会话闲置超时断开后,下次启动只需重新运行代码,会自动检测已下载文件并续传
  • 路径验证:确保Drive目标目录存在,可提前用os.makedirs(os.path.dirname(file_name), exist_ok=True)创建目录

内容的提问来源于stack exchange,提问作者Ritzy Dev

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:30:49