2

when i want download jpeg in python with this code:

def download(url, dest):
    s = urllib2.urlopen(url)
    content = s.read()
    s.close()
    d = open(dest,'w')
    d.write(content)
    d.close()

the file on hdd is not readable but when i open jpeg in mozilla its ok, i am using windows and python 2.6 some solutions? thanks

1
  • 1
    Surely a function that does the downloads for you would be a better answer? This one allows for a report hook, and a download location to be set Commented Mar 3, 2011 at 22:18

3 Answers 3

8

You are opening the file in text mode and corrupting it. Python is interpreting certain byte sequences as EOL characters and writing them out as the appropriate EOL for that operating system. You need to tell Python to open the destination file in binary mode.

Change d = open(dest,'w') to d = open(dest,'wb') and everything will just work.

Sign up to request clarification or add additional context in comments.

Comments

6

For 2.x?

import urllib
urllib.urlretrieve(url)

Comments

5

Try opening the output file in binary mode:

d = open(dest,'wb')

(This only matters ion Windows or in Python 3.x. You are obviously using Python 2.x, but you might be on Windows).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.