Python 3.5中urllib.urlretrieve的替代方案

Python 3.5中urllib.urlretrieve的替代方案,python,python-3.x,urllib2,Python,Python 3.x,Urllib2,我目前正在UDACITY上一门关于机器学习的课程。在那里,他们用Python2.7编写了一些代码,但由于我目前使用的是Python3.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

我目前正在UDACITY上一门关于机器学习的课程。在那里,他们用Python2.7编写了一些代码,但由于我目前使用的是Python3.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

你会用。请注意,此函数“在将来某个时候可能会被弃用”,因此您最好使用不太可能被弃用的接口:

# 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)

对于足够小的文件,您只需
整个过程,然后完全放弃循环。

我知道这个问题早就得到了回答,但我将为未来的任何观众做出贡献

建议的解决方案很好,但主要问题是,如果使用无效URL,它会生成空文件

作为解决此问题的一种方法,以下是我如何调整代码:

def getfile(url,filename,timeout=45):
    with contextlib.closing(urlopen(url,timeout=timeout)) as fp:
        block_size = 1024 * 8
        block = fp.read(block_size)
        if block:
            with open(filename,'wb') as out_file:
                out_file.write(block)
                while True:
                    block = fp.read(block_size)
                    if not block:
                        break
                    out_file.write(block)
        else:
            raise Exception ('nonexisting file or connection error')
我希望这对你有所帮助。

你可以用它神奇地将url ByTestStream复制到文件中

    import urllib.request
    import shutil
    
    url = "http://www.somewebsite.com/something.pdf"
    output_file = "save_this_name.pdf"
    with urllib.request.urlopen(url) as response, open(output_file, 'wb') as out_file:
        shutil.copyfileobj(response, out_file)

来源:

如果
请求
是可用的,我会用它,有人回答并为我工作。我需要的是urllib.request.urlRetrieve,而不是urllib.urlRetrieve,但我的天啊,这太难看了。