Why I can’t upload the whole image file using urllib2.urlopen ()

When I run the following code, it seems that it only downloads the first bit of the file and then exits. By chance, I get error 10054, but usually it just exits without getting the whole file. My internet connection is a crappy wireless connection, and I often get broken downloads in large files in firefox, but my browser has no problem getting the 200,000 image file. I am new to python and programming in general, so I wonder what nuance I have lacks.

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
+5
source share
1 answer

To write a binary file on Windows, you need to explicitly open it as a binary, i.e.:

xkcdpicfile=open("C:\\Documents and Settings\\John Gann\\Desktop\\xkcd.png",
                 "wb")

b : "wb", "w"!

print chunk, , , . - - , , print repr(chunk), . - , , . len(chunk) , , .

+10

All Articles