python - Python 3.5 中 urllib.urlretrieve 的替代方案

标签 python python-3.x urllib2

我目前正在 UDACITY 学习机器学习类(class)。他们在那里用 python 2.7 编写了一些代码,但由于我目前使用的是 python 3.5,所以出现了一些错误。这是代码

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 。

  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。

最佳答案

你会使用 urllib.request.urlretrieve .请注意,此功能“可能会在将来的某个时候被弃用”,因此您最好使用不太可能被弃用的接口(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)

对于足够小的文件,您可以只读取写入 整个文件,然后完全放弃循环。

关于python - Python 3.5 中 urllib.urlretrieve 的替代方案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38358521/

相关文章:

python - 为什么 lambda 函数中的括号会导致 Python 3 上的语法错误?

python - 在多个目录中按名称搜索文件?

Python 2.7 (urllib2)。如何使用 SSL HTTPS 代理?

python - 使用请求获取 .onion 域

python - 如何在if语句中退出python脚本

python - 使用 .read() 从文件对象中提取文本

python - 解决 PyDev 中 Python 模块警告的无效名称

python - 确定 TCP listen() 队列中当前积压的连接数

python - 字典记录在打印时被截断

python - NumPy 中可以使用分层广播吗?