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

Python代码拉取GitHub公开仓库文件至本地目录失败,求解决

问题分析与修复方案

代码核心问题

  • 未导入os模块:代码中使用了os.path.join但未导入该模块,会触发NameError
  • 仓库URL参数错误:传入的是文件的GitHub网页链接,而非仓库根地址,且路径拼接逻辑混乱
  • 获取内容错误:GitHub的/blob/路径返回的是带网页UI的内容,不是文件原始数据,无法直接保存为目标文件

修复后的代码

import requests
import os  # 补充导入os模块

def pull_files(repo_owner, repo_name, branch, directory, file_path_in_repo):
    """
    从指定GitHub仓库拉取特定文件到本地目录。

    参数:
      repo_owner: GitHub仓库所有者用户名
      repo_name: GitHub仓库名称
      branch: 目标分支名(如main)
      directory: 本地存储文件的目录
      file_path_in_repo: 文件在仓库中的完整路径(如.github/workflows/bard.py)
    """
    # 构造原始文件的请求链接
    raw_file_url = f"https://raw.githubusercontent.com/{repo_owner}/{repo_name}/{branch}/{file_path_in_repo}"
    response = requests.get(raw_file_url)
    if response.status_code != 200:
        raise Exception(f"获取文件失败,状态码: {response.status_code}")

    # 确保本地目标目录存在
    os.makedirs(directory, exist_ok=True)
    # 提取文件名,避免路径嵌套问题
    local_file_path = os.path.join(directory, os.path.basename(file_path_in_repo))
    with open(local_file_path, "wb") as f:
        f.write(response.content)

if __name__ == "__main__":
    repo_owner = "Hackerash008"
    repo_name = "Test"
    branch = "main"
    directory = "C:\\Users\\HP"
    file_path_in_repo = ".github/workflows/bard.py"
    pull_files(repo_owner, repo_name, branch, directory, file_path_in_repo)

关键修复说明

  • 拆分仓库参数:将仓库所有者、名称、分支单独传入,避免URL拼接出错
  • 改用原始文件链接:通过raw.githubusercontent.com获取文件原始内容,而非网页
  • 新增目录检查:用os.makedirs确保本地目录存在,防止写入失败
  • 优化文件名处理:从仓库文件路径中提取文件名,保证本地保存的文件名正确

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 19:22:35