如何使用Google colab将文件下载到Google云端硬盘?

时间:2020-06-09 14:46:28

标签: python google-colaboratory downloadfile

我一直在使用此代码通过Google Drive挂载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)

2 个答案:

答案 0 :(得分:3)

我更喜欢使用!wget方法。

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

这种方式要容易得多。

答案 1 :(得分:0)

请勿将文件下载到Google云端硬盘中,因为在Colab中访问Google云端硬盘(尤其是在其中写入文件)会产生开销。

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