Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download files over HTTP via python-urllib2 correctly?

Tags:

python

file

image

I've written parser on python to download images from Internet:

import urllib2

for i in xrange(1,10):
  r = urllib2.urlopen('http://example.com/'+str(i)+'.gif'))
  f = open('C:\\' + str(i) + '.gif', 'w+')
  f.write(r.read())
  f.close()

Images can't be opened. Windows says 'Error while building image'. But I've found that every line of received file less on 1 byte than this line of original file, but both look similar. How to download correct file?

like image 319
shunter Avatar asked Jul 01 '11 18:07

shunter


2 Answers

When working with windows you may need to put the "binary" flag b in open...

f = open(r'C:\\'+str(i)+'.gif','wb')
like image 193
Andrew White Avatar answered Nov 14 '22 22:11

Andrew White


On Windows you need to specify 'wb', not 'w+'

like image 43
Andreas Jung Avatar answered Nov 15 '22 00:11

Andreas Jung