-1

I used shutil to download an image from an URL and it works fine but it downloads the images on the project directory. Is it possible to specify a directory so that the program saves it there?

I searched for a solution on StackOverflow but only found a solution using urllib urlretrieve which does not really relate to what I am trying to do. Thank you

import requests
import shutil
import os
import urllib.request

url = "https://www.lamborghini.com/sites/it-en/files/DAM/lamborghini/facelift_2019/homepage/families-gallery/2022/04_12/family_chooser_tecnica_m.png"

file_name = input("save image as :")
file_name += ".jpg"

res = requests.get(url, stream = True)
if res.ok:
    with open(file_name,"wb") as f:
        shutil.copyfileobj(res.raw,f)
    print("image succesfully downloaded ", file_name)
else:
    print("Download failed: status code {}\n{}".format(res.status_code, res.text))

or using urllib


f = open("sadasd.png", "wb")
f.write(urllib.request.urlopen(r"https://www.lamborghini.com/sites/it-en/files/DAM/lamborghini/facelift_2019/homepage/families-gallery/2022/04_12/family_chooser_tecnica_m.png").read())
f.close()

Sloth99
  • 23
  • 8
  • Easy 2 second search on google: https://stackoverflow.com/questions/3042757/downloading-a-picture-via-urllib-and-python – Ilya Jun 26 '22 at 18:28
  • Does this answer your question? [Downloading a picture via urllib and python](https://stackoverflow.com/questions/3042757/downloading-a-picture-via-urllib-and-python) – Ilya Jun 26 '22 at 18:31
  • @ilya Hello Ilya, I looked at this one but If I understood correctly this person is asking how to download the file properly because he/she could not download the file. I have no problem with downloading it but I need to download it to a specific file. He/she asked later how to download it to a specific folder but people did not answer and rather said keep posts to 1 question only. – Sloth99 Jun 26 '22 at 18:44

1 Answers1

1

I found a simpler solution. So I changed my code to use only Urllib. What I was missing was the forward slash at the end of the destination path which is C:users\user\Pictures\test/.

To add another piece of information as you can see in the code block urlretrieve uses the second argument as a location that you want to save.

import urllib.request

def download_jpg(url, file_path, file_name):
    full_path = file_path + file_name + ".jpg"
    urllib.request.urlretrieve(url, full_path)


url = input("Enter img URL to download: ")
file_name = input("Enter file name to save as: ")

download_jpg(url, r"C:\Users\User\Pictures\test/", file_name )
Sloth99
  • 23
  • 8