【问题标题】:Load .zip file from GitHub in Google Colab在 Google Colab 中从 GitHub 加载 .zip 文件
【发布时间】:2021-06-04 20:20:57
【问题描述】:

我的 GitHub 存储库中有一个 zip 文件。我想将它加载到我的 Google Colab 文件中。我有它的网址,可以从那里下载它,例如https://raw.githubusercontent.com/rehmatsg/../master/...zip

我使用这种方法将文件下载到 Google Colab 中

from google.colab import files

url = 'https://raw.githubusercontent.com/user/.../master/...zip'
files.download(url)

但我得到了这个错误

FileNotFoundError                         Traceback (most recent call last)
<ipython-input-5-c974a89c0412> in <module>()
      3 from google.colab import files
      4 
----> 5 files.download(url)

/usr/local/lib/python3.7/dist-packages/google/colab/files.py in download(filename)
    141       raise OSError(msg)
    142     else:
--> 143       raise FileNotFoundError(msg)  # pylint: disable=undefined-variable
    144 
    145   comm_manager = _IPython.get_ipython().kernel.comm_manager

FileNotFoundError: Cannot find file: https://raw.githubusercontent.com/user/.../master/...zip

Google Colab 中的文件是临时文件,因此我无法每次都上传。这就是我想在项目的 GitHub 存储库中托管文件的原因。 将文件下载到 Google Colab 的正确方法是什么?

【问题讨论】:

  • 查看您的链接,您的第一个链接的用户名是rehmatsg。第二个有user。所以我认为这里的问题是您提供了错误的 URL。
  • 不,实际上我的网址是有效的。我的问题中的这个只是一个例子

标签: python github google-colaboratory


【解决方案1】:

使用“wget”bash 命令。只需打开 Github 项目并转到下载为 zip 选项(在右上角)。然后,复制 url 并使用“wget”命令。

!wget https://github.com/nytimes/covid-19-data/archive/refs/heads/master.zip

!unzip /content/master.zip

祝你好运。

【讨论】:

    【解决方案2】:

    假设 GitHub repo https://github.com/lukyfox/Datafiles 包含文件夹 digits 和两个 zip 文件 digits.zipdigits_small.zip。要从 GitHub 存储库(不是整个存储库或文件夹,而只是 digits.zip)下载并解压缩某些 zip 文件到 Google Colab 会话存储中:

    1. 转到您要下载的 zip 文件(即https://github.com/lukyfox/Datafiles/blob/master/digits/digits.zip
    2. 定位按钮下载并复制其地址(人民币->复制链接地址),如上例复制地址为https://github.com/lukyfox/Datafiles/raw/master/digits/digits.zip
    3. 转到 Google colab 文件并使用带有复制地址的!wget 命令进行下载,并使用!unzip 将文件解压缩到会话存储中:

    !wget https://github.com/lukyfox/Datafiles/raw/master/digits/digits.zip
    !unzip /content/digits.zip

    您也可以在下载后重命名文件或为解压缩的数据指定文件夹名称。

    您可能会注意到可下载地址与 zip 文件地址略有不同。事实上,将 blob 替换为 raw 就足以获得任何 zip 文件的正确地址。

    【讨论】:

      【解决方案3】:

      我不使用 Google Colab,但我查看了这个 description。了解google.colab.download 选项是下载 Google Colab 文件。它不是用于下载任何文件。如果此文件是公开的,您可以使用其他库来检索该文件。例如,您可以使用urllib

      from urllib.request import urlretrieve
      urlretrieve(url)
      

      如果您决定需要更多文件并使用代码,请考虑关于 git clone 的其他答案

      【讨论】:

        【解决方案4】:

        您可以这样做来克隆整个存储库。

        !git clone https://personalaccesstoken@github.com/username/reponame.git
        

        这将创建一个名为reponame 的文件夹,如果您有很多文件要下载,这会很方便。 personalaccesstoken 允许访问私有存储库。

        【讨论】:

        • 如果它是私有的,您仍然可以克隆。你只需要找到一种方法来传递 API 令牌。
        • 您可以在 Github 中创建个人访问令牌并使用我想的。编辑完成...
        • 存储库包含许多大文件。下载整个 repo 是不可行的。
        • 根据我的经验,下载速度很快,您可以使用许多 Gb 的空间。