python下載大文件代碼

pythopen 9年前發布 | 4K 次閱讀 Python

如果下載小文件,可以直接使用urllib.urlretrieve方法:

import urllib
urllib.urlretrieve ("http://www.example.com/songs/mp3.mp3", "mp3.mp3")

但是如果下載的文件尺寸很大,就不適合直接urlretrieve了。我們需要按塊讀取文件來下載:

import urllib2

url = "http://download.thinkbroadband.com/10MB.zip"

file_name = url.split('/')[-1] u = urllib2.urlopen(url) f = open(file_name, 'wb') meta = u.info() file_size = int(meta.getheaders("Content-Length")[0]) print "Downloading: %s Bytes: %s" % (file_name, file_size)

file_size_dl = 0 block_sz = 8192 while True: buffer = u.read(block_sz) if not buffer: break

file_size_dl += len(buffer)
f.write(buffer)
status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
status = status + chr(8)*(len(status)+1)
print status,

f.close()</pre>

 本文由用戶 pythopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!