Delete all the png images from a folder in Python

In this tutorial, I will discuss how you can delete all the png images from a specific folder using Python. For this we need to import os module, it’s a built-in module of Python so you need not to install it. We’ll use two methods of this module to solve this problem, the first one is os.listdir() method and the second one is os.remove () method. os.listdir() method returns a list of files immediately present in a given directory. Remember it only lists files or directories immediately under a given directory. It doesn’t list all the files/directories recursively under a given directory. os.remove() method simply removes the specified file path. In case of inaccessible or invalid file paths and names it simply raises an error called OSError.

Now let’s see how we can use this two methods to solve our problem:

#importing os module
import os

#providing the path of the folder
#r = raw string literal
folder_path = (r'C:\Users\sourav\Desktop\test')

#using listdir() method to list the files of the folder
test = os.listdir(folder_path)

#taking a loop to remove all the images
#using ".png" extension to remove only png images
#using os.remove() method to remove the files

for images in test:
    if images.endswith(".png"):
        os.remove(os.path.join(folder_path, images))

Output: It’ll show nothing but it’ll delete all the png files of the given folder path.

We can change the extension to any other file format to remove those specific files from the directory.

Remember, it’ll not send files to the trash or recycle bin but it’ll delete the files permanently.

Read also: How to iterate over files in a given directory in Python

Leave a Reply

Your email address will not be published. Required fields are marked *