且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python 3.5 中 urllib.urlretrieve 的替代方案

更新时间:2021-11-04 01:54:32

你会使用 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.