下载图像,想要保存到文件夹,检查文件是否存在

Bla*_*man 4 python file-io download

所以我有一个记录集(sqlalchemy)我正在循环的产品,我想下载一个图像并将其保存到一个文件夹.

如果该文件夹不存在,我想创建它.

另外,我想首先检查文件夹中是否存在图像文件. 如果是,请不要下载只跳过该行.

/myscript.py
/images/
Run Code Online (Sandbox Code Playgroud)

我希望images文件夹是与我的脚本文件在同一目录中的文件夹,无论它存储在何处.

我到目前为止:

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
Run Code Online (Sandbox Code Playgroud)

Phi*_*ipp 10

我想你可以在urllib.urlretrieve这里使用:

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)
Run Code Online (Sandbox Code Playgroud)