Skip to content

Instantly share code, notes, and snippets.

@dheaney
Created December 27, 2012 05:18
Show Gist options
  • Save dheaney/4385674 to your computer and use it in GitHub Desktop.
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.
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, ' ')
Copy link

ghost commented Dec 13, 2016

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment