Question

I download an image from the web under linux (debian) without problems, using the code snippet below. When I run the exact same code in windows, the resulting image is garbled. What is the problem?

import urllib, os
url = "http://www.crummy.com/software/BeautifulSoup/10.1.jpg"
contents = urllib.urlopen (url).read()
fn = os.path.join(os.path.expanduser("~"), "winimagetest")
fh = open(fn, "w");fh.write(contents);fh.close()

The target system is Windows 7, 64 bit, and the python installation is 32 bit. (This does not matter, the same garbled output happens if python is 64 bit).

I've uploaded the garbled image:

Was it helpful?

Solution

For Windows, you need to open the file in binary mode since Windows distinguishes between binary and text files. It works on Linux as-is because Linux makes no such distinction.

Change the line

fh = open(fn, "w")

to

fh = open(fn, "wb")

You may also want to consider doing the following:

with open(fn, "wb") as fh:
    fh.write(contents)

As it will handle closing the file for you in case of any type of exception.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top