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”,“”
  2. “Christina2.jpg”,“”
  3. “Christina3.jpg”,“”
  4. “Christina4.jpg”,“”
  5. “Christina5.jpg”,“”

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

  1. import csv
  2. import requests
  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 =
  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.


Add a Comment