How do I write a Python code to download images from 100 URLs stored in a .CSV file?

Posted by:

Suppose you have a file photos.csv like this:

  1. “Christina1.jpg”,“http://ultraimg.com/images/Christina-Hendricks-Images2.jpg”
  2. “Christina2.jpg”,“http://www.bolsamania.com/seriesadictos/wp-content/uploads/2015/07/Christina-Hendricks.jpg”
  3. “Christina3.jpg”,“https://s-media-cache-ak0.pinimg.com/736x/10/8f/b3/108fb3f483d2b0ee5cd50db4ffc751ab.jpg”
  4. “Christina4.jpg”,“http://www.speakerscorner.me/wp-content/uploads/2016/04/christina5.jpg”
  5. “Christina5.jpg”,“http://i.dailymail.co.uk/i/pix/2013/04/05/article-2304737-191E7594000005DC-598_634x782.jpg”

You can download the images with this code (I tried succesfully):

  1. import csv
  2. import requests
  3.  
  4. with open(‘fotos.csv’) as csvfile:
  5. csvrows = csv.reader(csvfile, delimiter=‘,’, quotechar=‘”‘)
  6. for row in csvrows:
  7. filename = row[0]
  8. url = row[1]
  9. print(url)
  10. result = requests.get(url, stream=True)
  11. if result.status_code == 200:
  12. image = result.raw.read()
  13. open(filename,“wb”).write(image)

If you need no more than code, this will suffice.

For explanations: csv and requests are Python packages, just to read CSV files and to make http calls, respectively.

You must first open the text file (line 4). The handler is the csvfile variable. You’ll use it to feed the reader() method of the csv package. It is not necessary to know what it does, just use it to get a list of row-data you can iterate (line 6). Every element in row contains a field of the csv row.

The requests package has the get() method to retrieve url content. Usually the http body is downloaded in-the-fly, the stream=True flag defers the download until the use of read() (line 12).

The result (line 10) is a structure – one of the fields (status_code, line 11) gives you info about the http connection (200 is the number for OK).

The bytes of the image are downloaded with the read() method of the result.raw property (line 12).

Then, finally, you open a file to write bytes (“wb” flag in line 13) and apply the write() method to effectively fill the file.

0

Add a Comment