Ian Baker Ian Baker - 7 months ago 18
Python Question

Cannot download images with dynamic input python

I am trying to download images with Python and I found some good answers in Downloading a picture via urllib and python , but when I try to use easygui to type in a url the image just opens in my browser instead of downloading the image

Here is my code:

import easygui as eg
import os
import urllib

url = eg.enterbox('Enter url: ', 'URL Choice')
name = eg.enterbox('Enter name: ', 'Name')

def DownloadImage(URL, name):
try:
image = urllib.urlopen(URL)
if image.headers.maintype == 'image':
buf = image.read()
path = os.getcwd() + 'C:\Users\USER\ImageGrabber\Pics'
file_path = '%s%s' % (path,name+'.jpg')
downloaded_image = file(file_path, 'wb')
downloaded_image.write(buf)
image.close()
else:
return False
except:
print 'Cannot access file'
return False
return True

DownloadImage(url,name)


I have used the type function and the result from the boxes are strings, so I do not know why it will not work

Edit: forgot to include variables

Answer

Your target path is wrong os.getcwd() gives you the current working directory and you are appending an absolute directory.

So let's say your script is in C:\myscript.py, os.getcwd() will return C:\ and you are appending to that C:\Users\USER\ImageGrabber\Pics, the result will be C:\C:\Users\USER\ImageGrabber\Pics which is an invalid path therefore going to the exception.

path='C:\Users\USER\ImageGrabber\Pics\' 
# The last '\' is important

that should work

edit

I cannot test because I'm running linux but the directory may need to be like this

path='C:/Users/USER/ImageGrabber/Pics/'
Comments