Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Downloading an image, want to save to folder, check if file exists

So I have a recordset (sqlalchemy) of products that I am looping, and I want to download an image and save it to a folder.

If the folder doesn't exist, I want to create it.

Also, I want to first check if the image file exists in the folder. If it does, don't download just skip that row.

/myscript.py
/images/

I want the images folder to be a folder in the same directory as my script file, wherever it may be stored.

I have so far:

q = session.query(products)

for p in q:
     if p.url:
          req = urllib2.Request(p.url)
          try:
                 response = urllib2.urlopen(req)
                 image = response.read()

                 ???
          except URLError e:
                 print e
like image 297
Blankman Avatar asked Dec 22 '22 00:12

Blankman


1 Answers

I think you can just use urllib.urlretrieve here:

import errno
import os
import urllib

def require_dir(path):
    try:
        os.makedirs(path)
    except OSError, exc:
        if exc.errno != errno.EEXIST:
            raise

directory = os.path.join(os.path.dirname(os.path.abspath(__file__)), "images")
require_dir(directory)
filename = os.path.join(directory, "stackoverflow.html")

if not os.path.exists(filename):
    urllib.urlretrieve("http://stackoverflow.com", filename)
like image 175
Philipp Avatar answered Dec 26 '22 11:12

Philipp