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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With