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

如何将Google Drive中Zip文件的指定子集导入Google Colab?

实现方法:从Google Drive的大型Zip文件中提取指定文件夹的部分图片到Colab

第一步:挂载Google Drive到Colab

先将你的Google Drive挂载到Colab环境,才能访问其中的Zip文件:

from google.colab import drive
drive.mount('/content/drive')

执行后按提示完成授权即可。


方法一:用Shell命令快速筛选提取(适合快速操作)

通过unzip命令直接指定要提取的文件夹,再从中选取前200张图片,无需完整解压整个大Zip:

# 1. 仅提取folder1和folder4到临时目录(安静模式避免冗余输出)
unzip -q "/content/drive/MyDrive/MyBigFile.zip" "folder1/*" "folder4/*" -d "/content/temp_extract"

# 2. 创建目标目录,从folder1取前200张图片
mkdir -p "/content/target_images/folder1"
ls -1 "/content/temp_extract/folder1/"*.png | head -200 | xargs cp -t "/content/target_images/folder1"

# 3. 从folder4取前200张图片
mkdir -p "/content/target_images/folder4"
ls -1 "/content/temp_extract/folder4/"*.png | head -200 | xargs cp -t "/content/target_images/folder4"

# 4. 清理临时提取的大文件夹(节省Colab磁盘空间)
rm -rf "/content/temp_extract"

如果需要随机选取200张而非按文件名顺序,将head -200替换为shuf -n 200即可。


方法二:用Python精确控制提取(节省磁盘空间,适合超大型Zip)

通过Python的zipfile库直接读取Zip文件内容,无需提前解压整个文件夹,更适合磁盘空间有限的场景:

import zipfile
from pathlib import Path
import random  # 如需随机选取图片则导入

# 配置路径和提取规则
zip_file_path = "/content/drive/MyDrive/MyBigFile.zip"
target_root_dir = "/content/target_images"
extract_rules = {"folder1": 200, "folder4": 200}  # 键为文件夹名,值为要提取的图片数量

# 创建目标根目录
Path(target_root_dir).mkdir(parents=True, exist_ok=True)

# 打开Zip文件并筛选提取
with zipfile.ZipFile(zip_file_path, 'r') as zip_ref:
    for folder_name, img_count in extract_rules.items():
        # 筛选当前文件夹下的所有PNG文件
        all_png_files = [
            file_path for file_path in zip_ref.namelist()
            if file_path.startswith(f"{folder_name}/") and file_path.endswith(".png")
        ]
        # 选取指定数量的图片:按顺序取前N张,如需随机则用下一行替换
        selected_files = all_png_files[:img_count]
        # selected_files = random.sample(all_png_files, img_count)
        
        # 创建当前文件夹的目标目录
        target_folder = Path(target_root_dir) / folder_name
        target_folder.mkdir(exist_ok=True)
        
        # 逐个提取选中的文件
        for file in selected_files:
            zip_ref.extract(file, target_folder)

这种方式只会提取你需要的200张图片,不会占用额外空间存储整个文件夹的内容。


注意事项

  • 确保MyBigFile.zip的路径正确,若不在Drive根目录,需修改代码中的路径(比如/content/drive/MyDrive/xxx/MyBigFile.zip)。
  • Colab的临时磁盘空间有限,方法一的临时解压步骤如果遇到空间不足,优先使用方法二。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 17:50:22