Created
December 27, 2012 05:18
-
-
Save dheaney/4385674 to your computer and use it in GitHub Desktop.
Download files with urllib2. Display percentage of file downloaded based off of bytes. Write file chunks instead of holding data in memory. Awesome.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib2 | |
import sys | |
url = "http://example.com/file.mp3" | |
request = urllib2.urlopen(url) | |
file = open('file.mp3', 'wb') | |
filesize = int(request.info().getheaders("Content-Length")[0]) | |
print "Downloading: %s Bytes: %s" % (url.split('/')[-1], filesize) | |
size = 0 | |
block_sz = 131072 | |
while True: | |
buffer = request.read(block_sz) | |
if not buffer: | |
break | |
size += len(buffer) | |
percentage = float(float(size) / float(filesize)) * 100 | |
file.write(buffer) | |
print "Downloaded: " + ("%.2f" % percentage) + " %\t\t\r", | |
sys.stdout.flush() | |
file.close() | |
print "Finished!".ljust(20, ' ') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks