Ian Baker Ian Baker - 1 year ago 39
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):
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')
return False
print 'Cannot access file'
return False
return True


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


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.

# The last '\' is important

that should work


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