Search code examples
pythonimagepython-requestspython-os

Saving images to a folder in the same directory Python


I have written this code that takes a URL and downloads the image. I was wondering how can I save the images to a specific folder in the same directory?

For example, I have a folder named images in the same directory. I wanted to save all the images to that folder.

Below is my code:

import requests
import csv
    
with open('try.csv', 'r') as csv_file:
    csv_reader = csv.reader(csv_file)
    for rows in csv_reader:
        image_resp = requests.get(rows[0])
        with open(rows[1], 'wb') as image_downloader:
            image_downloader.write(image_resp.content)

Solution

  • Looking for this?

    with open(os.path.join("images", rows[1]), 'wb') as fd:
        for chunk in r.iter_content(chunk_size=128):
            fd.write(chunk)
    

    See official docs here: os.path.join

    Requests specific stuff from https://2.python-requests.org/en/master/user/quickstart/#raw-response-content

    PS: You might want to use a connection pool and/or multiprocessing instead of the for rows in csv_reader, in order to have many concurrent requests.