Python Filter Files In A Directory

Do you like this?

This snippet helps you filter files in a directory.


To make it easy to understand, I will show you how to filter JPG images in the current folder below. You can add any other extensions of your interest.

import os

image_extensions = ['JPG'] # constants

def filterImageFiles(filenames):
    result = []
    for filename in filenames: # loop through all the files and folders
        if os.path.isfile(os.path.join(os.path.abspath("."), filename)): # check whether the current object is a file or not
            filename_text, filename_ext= os.path.splitext(filename)
            filename_ext= filename_ext[1:].upper()
            if filename_ext in image_extensions: # check whether the current object is a JPG file
    return result

image_files = filterImageFiles(os.listdir('.')) # list all the files and folders in the current directory

comments powered by Disqus