How to iterate through images in a folder Python?
Last Updated :
21 Jul, 2022
In this article, we will learn how to iterate through images in a folder in Python.
Example 1: Iterating through .png only
- At first we imported the os module to interact with the operating system.
- Then we import listdir() function from os to get access to the folders given in quotes.
- Then with the help of os.listdir() function, we iterate through the images and printed the names in order.
- Here we have mentioned only .png files to be loaded using the endswith() function.
Python3
import os
from os import listdir
folder_dir = "C:/Users/RIJUSHREE/Desktop/Gfg images"
for images in os.listdir(folder_dir):
if (images.endswith( ".png" )):
print (images)
|
Output:
Example 2: Iterating through all kinds of images
Here we have mentioned .png, .jpg, .jpeg files to be loaded using the endswith() function.
Python3
import os
from os import listdir
folder_dir = "C:/Users/RIJUSHREE/Desktop/Gfg images"
for images in os.listdir(folder_dir):
if (images.endswith( ".png" ) or images.endswith( ".jpg" )\
or images.endswith( ".jpeg" )):
print (images)
|
Output:
- At first, we imported the pathlib module from Path.
- Then we pass the directory/folder inside Path() function and used it .glob(‘*.png’) function to iterate through all the images present in this folder.
Python3
from pathlib import Path
folder_dir = 'Gfg images'
images = Path(folder_dir).glob( '*.png' )
for image in images:
print (image)
|
Output:
- At first we imported the glob module.
- Then with the help of glob.iglob() function we iterate through the images and print the names in order.
- Here we have mentioned .png files to be loaded using the endswith() function.
Python3
import glob
folder_dir = 'Gfg images'
for images in glob.iglob(f '{folder_dir}/*' ):
if (images.endswith( ".png" )):
print (images)
|
Output:
Share your thoughts in the comments
Please Login to comment...