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

如何通过GitHub API下载仓库指定文件夹的全部内容(含子文件夹)

解决GitHub指定文件夹下载问题的几种方法

方法1:Git稀疏检出(git sparse-checkout)

这是最高效的原生Git方案,无需克隆整个仓库,仅拉取目标文件夹内容:

# 初始化本地仓库
git init my-repo
cd my-repo
# 启用稀疏检出功能
git config core.sparseCheckout true
# 写入要下载的文件夹路径(支持多个,每行一个)
echo "people/" >> .git/info/sparse-checkout
# 关联远程仓库
git remote add origin https://github.com/<仓库所有者>/<仓库名>.git
# 拉取指定分支内容(比如main分支)
git pull origin main

方法2:GitHub CLI(gh)快速下载

如果已安装GitHub CLI并登录,可直接用内置命令指定文件夹下载:

gh repo download <仓库所有者>/<仓库名> --dir people

方法3:GitHub API递归遍历下载

适合需要自定义下载逻辑的场景,通过递归调用API遍历文件夹及子文件:

import requests
import os

# 替换为你的信息
GITHUB_TOKEN = "你的GitHub令牌"
REPO_OWNER = "仓库所有者"
REPO_NAME = "仓库名"
TARGET_FOLDER = "people"

def download_folder(path):
    api_url = f"https://api.github.com/repos/{REPO_OWNER}/{REPO_NAME}/contents/{path}"
    headers = {"Authorization": f"token {GITHUB_TOKEN}"}
    resp = requests.get(api_url, headers=headers)
    resp.raise_for_status()
    contents = resp.json()

    for item in contents:
        if item["type"] == "file":
            # 创建本地目录
            local_path = f"./{TARGET_FOLDER}/{item['path']}"
            os.makedirs(os.path.dirname(local_path), exist_ok=True)
            # 下载文件
            file_resp = requests.get(item["download_url"], headers=headers)
            file_resp.raise_for_status()
            with open(local_path, "wb") as f:
                f.write(file_resp.content)
        elif item["type"] == "dir":
            download_folder(item["path"])

download_folder(TARGET_FOLDER)

注意:使用API时需关注GitHub的速率限制,添加令牌可提升限额。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 18:15:02