How to delete all files with a specific extension in Python

Deleting all files with a specific extension searches a folder for files with that extension and removes them.

Solution for How to delete all files with a specific extension in Python : You can use str.endswith() and os.remove() to remove all files with a specific extension Use os.listdir(path) to return a list of all the files in a directory, path. Use a list comprehension and str.endswith(suffix) to return a filtered list of files that have the extension, “suffix”.

Loop over the filtered list and use os.path.join(a, filename) to create a path using the directory path as a, and filename as the file name. Use os.remove(path) to remove the file with the new path as path.


how-to-delete-all-files-with-a-specific-extension-in-python