Python 3.5 中 urllib.urlretrieve 的替代方案 [英] Alternative of urllib.urlretrieve in Python 3.5

查看:33
本文介绍了Python 3.5 中 urllib.urlretrieve 的替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在 UDACITY 学习机器学习课程.在那里,他们用 python 2.7 编写了一些代码,但由于我目前使用的是 python 3.5,我遇到了一些错误.这是代码

I am currently doing a course on machine learning in UDACITY . In there they have written some code in python 2.7 but as i am currently using python 3.5 , i am getting some error . This is the code

import urllib
url = "https://www.cs.cmu.edu/~./enron/enron_mail_20150507.tgz"
urllib.urlretrieve(url, filename="../enron_mail_20150507.tgz")
print ("download complete!") 

我试过 urllib.request .

I tried urllib.request .

  import urllib
  url = "https://www.cs.cmu.edu/~./enron/enron_mail_20150507.tgz"
  urllib.request(url, filename="../enron_mail_20150507.tgz")
  print ("download complete!")

但仍然给我错误.

urllib.request(url, filename="../enron_mail_20150507.tgz")
TypeError: 'module' object is not callable

我使用 PyCharm 作为我的 IDE.

I am using PyCharm as my IDE .

推荐答案

你会使用 urllib.request.urlretrieve.请注意,此功能可能会在未来某个时候被弃用",因此您最好使用不太可能被弃用的接口:

You'd use urllib.request.urlretrieve. Note that this function "may become deprecated at some point in the future", so you might be better off using the less likely to be deprecated interface:

# Adapted from the source:
# https://hg.python.org/cpython/file/3.5/Lib/urllib/request.py#l170
with open(filename, 'wb') as out_file:
    with contextlib.closing(urllib.request.urlopen(url)) as fp:
        block_size = 1024 * 8
        while True:
            block = fp.read(block_size)
            if not block:
                break
            out_file.write(block)

对于足够小的文件,您只需readwrite 整个文件并完全放弃循环.

For small enough files, you could just read and write the whole thing and drop the loop entirely.

这篇关于Python 3.5 中 urllib.urlretrieve 的替代方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆