Delete all the Png Images from a Folder in Python
Python is mostly used to automate tasks, including file management operations. Deleting all PNG images from a folder can be efficiently handled using Python. In this article, we will explore two different approaches to Deleting all the PNG images from a Folder in Python.
Delete all the PNG images from a Folder
Below are the possible approaches to Delete all the PNG images from a Folder in Python.
- Using os Module
- Using pathlib Module
Image Folder
Delete all the PNG images from a Folder Using OS Module
In this approach, we are using the os module to iterate through all files in the specified directory. For each file that ends with a .png extension, we use os.remove to delete the file and print a message confirming the deletion.
import os
folder_path = 'D:\GFG\day-JS\images'
for filename in os.listdir(folder_path):
if filename.endswith('.png'):
os.remove(os.path.join(folder_path, filename))
print(f"Deleted: {filename}")
Output:
Delete all the Png Images from a Folder Using pathlib Module
In this approach, we are using the pathlib module to handle file operations. We create a Path object for the specified directory, then use the glob method to find all .png files and unlink to delete each file, printing a message for each deleted file.
from pathlib import Path
folder_path = Path('D:\GFG\day-JS\images')
for file in folder_path.glob('*.png'):
file.unlink()
print(f"Deleted: {file.name}")
Output: