In this shot, we will discuss how to locally save an image using the
shutil libraries in Python.
Sometimes downloading image(s) becomes essential, especially when we are working on certain projects. Although we can manually download images, save them to our local drives, and use them in the required application, the process can be automated by writing simple Python scripts.
requests library in Python is mostly used for downloading any type of file using Python, and the
shutil library is used to save the file locally.
import requests import shutil import os # Image URL and filename image_url = "https://cdn.pixabay.com/photo/2016/11/19/14/00/code-1839406_960_720.jpg" filename = "pic.jpg" # Retrieving image without interruptions r = requests.get(image_url, stream = True) # Check image if r.status_code == 200: # Preventing the downloaded image’s size from being zero. r.raw.decode_content = True # Open a local file with open(filename,'wb') as f: shutil.copyfileobj(r.raw, f) print('Image successfully Downloaded: ',filename) else: print('Image Couldn\'t be retrieved') print(os.listdir())
In lines 2 and 3, we import the necessary libraries.
requestslibrary is used to get an image from the web.
shutillibrary is used to save the image locally.
In line 6, we declared the
url from which the image is downloaded.
In line 7, the file directory in which the image needs to be downloaded needs to be mentioned along with the image name, i.e., filename +
If no filename is mentioned, the picture gets downloaded in the same directory as that of the Python script file.
In line 10, we used the
get() method to retrieve the image from the specified URL.
stream = True ensures no interruptions during image retrieval.
In lines 13 to 24, we check if the image is retrieved successfully. In either case, a message of success or failure is printed.
In line 16, the value of
decode_content is set to
True, which ensures the downloaded image’s size will not be zero.
In lines 19 and 20, we open a local file with
wb (write binary) permission. Now, we create a file in binary-write mode locally and use the
shutil.copyfileobj() function to write our image to the file.
In lines 22 to 24, we print the success/failure message.
In line 26, we just print the files and folders available in the current directory. Here, we can verify that the image has been downloaded and saved.
View all Courses