如何使用 Google colab 下载文件到 Google 驱动器?

How to download files to Google Drive using Google colab?

我一直在使用此代码通过 Google 驱动器安装 Colab 并通过在下载 URL 中粘贴来下载任何文件,但我注意到即使文件很少也需要很长时间兆字节大小。有什么可以改进的吗

**First cell:**
from google.colab import drive
drive.mount('/content/gdrive')
root_path = 'gdrive/My Drive/' 

**Second cell:**
import requests  
file_url = "DOWNLOAD URL HERE"

r = requests.get(file_url, stream = True)  

with open("/content/gdrive/My Drive/FILE NAME HERE", "wb") as file:  
    for block in r.iter_content(chunk_size = 1024): 
         if block:  
             file.write(block)

不要将文件下载到 Google Drive,因为在 Colab 中访问 Google Drive 会产生开销,尤其是在其中写入文件。

如果此文件是临时文件,只需将其下载到 /tmp(或使用 tempfile.gettempdir 使代码更漂亮)。如果不是临时的,仍然考虑将其下载到临时文件夹,然后在下载结束时将其复制到云端硬盘(同时继续使用本地副本以提高速度)。

我更喜欢使用 !wget 方法。

!wget "Specify URL you want to download" -P "specify DIRECTORY where you want contents of URL"

例如

!wget "https://github.com/jbrownlee/Datasets/releases/download/Flickr8k/Flickr8k_Dataset.zip" -P "/content/drive/My Drive/imgcaptiongen/data"

这样就容易多了。