简体   繁体   中英

python 2.7 - How do I save images to a directory from a list of URLs in a CSV file

I have a CSV file with two columns, an image name and an image url...

EXAMPLE

Column A -- Column B

image1 -- http://www.image1.jpg

image2 -- http://www.image2.jpg

I am trying to use Python 2.7 to code a script that will take the CSV open it and save the images to a directory c:\\images, and name them using the image names that correspond to the image "image1", "image2", etc.

So far I have the following code:

import requests
import csv
import urllib2

images = csv.reader(open('image_urls.csv'))
for image in images:
    response = urllib2.urlopen(image[0])
    filename = 'image_{0}.{1}.jpg' 
    with open(filename,'wb') as w:
        w.write(response)
        w.close()

I have two issues:

1) I am not sure how to properly save the filename as the name in the first column of the CSV ("image1").

2) Running this code as is gives me the following errors:

Traceback (most recent call last):
  File "downloadimages.py", line 11, in <module>
    w.write(response)
TypeError: must be string or buffer, not instance

Can anyone help me to fix the error and the code so it saves the filename the way I want it.

Many Thanks in advance.

urllib2.urlopen returns a file like object not a string. So you need to read its contents:

with open(filename,'wb') as w:
    w.write(response.read())
    w.close()

You can use urlretrieve from urllib passing in the location to save

from urllib import urlretrieve

with open ('image_urls.csv') as images:
    images = csv.reader(images)
    img_count = 1  # start at 1
    for image in images:
        urlretrieve(image[0],
                'c:\\images\\image_{0}.jpg'.format(img_count)) # string formatting inserting count 
        img_count += 1 # increase count for each image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM