开发者

download file in python

开发者 https://www.devze.com 2023-02-14 12:29 出处:网络
when i want download jpeg in python with this code: def download(url, dest): s = urllib2.urlopen(url) content = s.read()

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 re开发者_如何学Goadable but when i open jpeg in mozilla its ok, i am using windows and python 2.6 some solutions? thanks


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.


For 2.x?

import urllib
urllib.urlretrieve(url)


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消