【问题标题】:How to download files to Google Drive using Google colab?如何使用 Google colab 将文件下载到 Google Drive?
【发布时间】:2020-06-09 14:46:28
【问题描述】:

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

【问题讨论】:

    标签: python download google-colaboratory


    【解决方案1】:

    我更喜欢使用!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"
    

    这样更容易。

    【讨论】:

    • 有什么方法可以使用python字符串而不是直接写URL?
    【解决方案2】:

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

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-24
    • 1970-01-01
    • 2022-08-20
    • 2018-10-22
    • 1970-01-01
    • 2021-04-30
    • 2020-10-21
    相关资源
    最近更新 更多