【问题标题】:Is there anyway I can download the file in Google colaboratory?无论如何我可以在 Google colaboratory 中下载文件吗?
【发布时间】:2023-03-12 07:59:01
【问题描述】:

我正在从这个 codelab 在 Google Colaboratory 中尝试 tensorflow, 我需要下载“http://download.tensorflow.org/example_images/flower_photos.tgz”这个文件来完成实验。

如何下​​载文件。无论如何上传tar文件而不在我的机器上下载它。

我试过这个方法

import urllib
testfile = urllib.URLopener()
testfile.retrieve("http://randomsite.com/file.gz", "file.gz")

这不起作用,wget 也找不到。任何人都请告诉我如何做到这一点。

【问题讨论】:

  • 试试import urllib.requesturllib.request.urlretrieve()

标签: python python-3.x jupyter-notebook google-colaboratory


【解决方案1】:

可能更简单:使用!wget,例如,使用以下命令执行单元格:

!wget https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png

将文件保存到虚拟机的本地文件系统。 (注意前面的!。这是一个信号,将行作为shell命令执行。)

【讨论】:

  • 您也可以在顶部设置%%bash 魔法以在一个单元格中使用多个 bash 命令
  • 您可以使用 wget 的 -O 标志来指定保存下载文件的位置,如下所示:wget -O mydir/output-file.png https://example.com/image.png
【解决方案2】:

阅读手册,他们有很好的例子和解释:urllib.request

下载:

>>> import os
>>> import urllib.request
>>> urllib.request.urlretrieve('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png', 'google.png')
('google.png', <http.client.HTTPMessage object at 0x7fba3c4cb908>)
>>> os.listdir()
['google.png']

只检查内容:

>>> with urllib.request.urlopen('http://www.python.org/') as f:
...     print(f.read(300))

【讨论】:

    猜你喜欢
    • 2019-05-21
    • 2018-04-29
    • 2018-05-24
    • 2018-07-08
    • 2019-09-12
    • 2018-10-14
    • 1970-01-01
    • 2020-09-25
    • 1970-01-01
    相关资源
    最近更新 更多