在 Google Colab 中从 GitHub 加载 .zip 文件

Load .zip file from GitHub in Google Colab

我的 GitHub 存储库中有一个 zip 文件。我想将它加载到我的 Google Colab 文件中。我有它的 url,可以从那里下载它,例如 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 的正确方法是什么?

您可以执行此操作以克隆整个存储库。

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

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

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

from urllib.request import urlretrieve
urlretrieve(url)

如果您决定需要更多文件并使用代码,请考虑有关 git clone

的其他答案

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

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

!unzip /content/master.zip

祝你好运。

假设 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. 定位按钮下载并复制其地址(RMB->复制link地址),如上例复制地址为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 文件地址略有不同。实际上应该足以用 raw 替换 blob 以获得任何 zip 文件的正确地址。