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

Google Colab读取Google Drive大量文件卡顿崩溃问题求助

Google Colab读取Google Drive大量文件挂起的解决办法

2023年5月起,Google Colab出现异常:从Google Drive读取文件时,打开不足38个文件就会卡住挂起,必须断开并删除运行时才能重启。使用PIL或cv2读取都会出现相同问题。

问题复现代码

import os
from google.colab import drive
from pathlib import Path
from tqdm import tqdm
import cv2
import glob

drive.mount('/content/drive')
MOUNTED_PATH = Path('/content/drive')
MYDRIVE_PATH = MOUNTED_PATH / "MyDrive"

# 填写存有大量png文件的文件夹路径
input_folder = "" #@param {type:"string"}
input_path = MYDRIVE_PATH / input_folder 

image_files = [str(f)
              for f in map(Path, sorted(glob.glob(f"{input_path}/*"))) 
              if f.is_file() and f.suffix in [".png"]
              ]
print(f"found {len(image_files)}")

# 运行到一定数量后挂起
for file in tqdm(image_files):
    img = cv2.imread(file)

复现输出

found 1968
  1%|          | 20/1968 [00:13<19:40,  1.65it/s]

程序在此处挂起,无法继续执行。

解决方案

核心原因是Google Drive挂载的文件系统存在文件句柄数量限制,连续读取挂载目录下的文件会快速耗尽可用句柄,导致进程卡死。最直接有效的解决办法是先将需要处理的文件复制到Colab本地存储,再从本地读取:

import shutil
from pathlib import Path
from google.colab import drive
from tqdm import tqdm
import cv2

drive.mount('/content/drive')
MYDRIVE_PATH = Path('/content/drive/MyDrive')
input_folder = "你的目标文件夹路径"
# 创建本地存储目录
local_dir = Path('/content/local_files')
local_dir.mkdir(exist_ok=True)

# 批量复制Drive中的文件到本地
source_files = list(MYDRIVE_PATH.joinpath(input_folder).glob("*.png"))
for f in tqdm(source_files):
    shutil.copy(f, local_dir / f.name)

# 从本地读取文件处理
local_files = list(local_dir.glob("*.png"))
for file in tqdm(local_files):
    img = cv2.imread(str(file))
    # 这里添加你的文件处理逻辑

补充说明

  • 复制到本地的文件会在Colab会话结束后自动清除,无需手动删除,下次运行重新复制即可。
  • 如果文件总大小超过Colab本地存储配额(通常约100GB),可以分批次复制处理,避免空间不足。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:22:24