Suppose you have a file photos.csv like this:
You can download the images with this code (I tried succesfully):
- import csv
- import requests
- with open(‘fotos.csv’) as csvfile:
- csvrows = csv.reader(csvfile, delimiter=‘,’, quotechar=‘”‘)
- for row in csvrows:
- filename = row
- url = row
- result = requests.get(url, stream=True)
- if result.status_code == 200:
- image = result.raw.read()
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.Share