Why can't I download a whole image file with urllib2.urlopen()

Posted by John Gann on Stack Overflow See other posts from Stack Overflow or by John Gann
Published on 2010-04-11T00:33:13Z Indexed on 2010/04/11 0:43 UTC
Read the original article Hit count: 517

Filed under:
|
|

When I run the following code, it only seems to be downloading the first little bit of the file and then exiting. Occassionally, I will get a 10054 error, but usually it just exits without getting the whole file. My internet connection is crappy wireless, and I often get broken downloads on larger files in firefox, but my browser has no problem getting a 200k image file. I'm new to python, and programming in general, so I'm wondering what nuance I'm missing.

import urllib2
xkcdpic=urllib2.urlopen("http://imgs.xkcd.com/comics/literally.png")
xkcdpicfile=open("C:\\Documents and Settings\\John Gann\\Desktop\\xkcd.png","w")
while 1:
    chunk=xkcdpic.read(4028)
    if chunk:
        print chunk
        xkcdpicfile.write(chunk)
    else:
        break

© Stack Overflow or respective owner

Related posts about python

Related posts about image