In this article, we will learn how to iterate through images in a folder in Python.
Method 1: Using os.listdir
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.
# import the modules
import os
from os import listdir
# get the path/directory
folder_dir = "C:/Users/RIJUSHREE/Desktop/Gfg images"
for images in os.listdir(folder_dir):
# check if the image ends with png
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.
# import the modules
import os
from os import listdir
# get the path or directory
folder_dir = "C:/Users/RIJUSHREE/Desktop/Gfg images"
for images in os.listdir(folder_dir):
# check if the image ends with png or jpg or jpeg
if (images.endswith(".png") or images.endswith(".jpg")\
or images.endswith(".jpeg")):
# display
print(images)
Output:

Method 2: Using pathlib module
- 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.
# import required module
from pathlib import Path
# get the path/directory
folder_dir = 'Gfg images'
# iterate over files in
# that directory
images = Path(folder_dir).glob('*.png')
for image in images:
print(image)
Output:

Method 3: Using glob.iglob()
- 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.
# import required module
import glob
# get the path/directory
folder_dir = 'Gfg images'
# iterate over files in
# that directory
for images in glob.iglob(f'{folder_dir}/*'):
# check if the image ends with png
if (images.endswith(".png")):
print(images)
Output:
