Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

download file in python

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

like image 806
user601987 Avatar asked Mar 17 '26 20:03

user601987


1 Answers

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.

like image 125
Sean Vieira Avatar answered Mar 19 '26 09:03

Sean Vieira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!