Home 9 The Art of Technology 9 Python Automation – Code Snippet – Return List of Files in Directory by Extension

Need to return list of files in directory based on the file extension?

This is a Python Code Snippet that will return a list of files based on extension from a directory including full path.

#Usage  yourlist = return_file_list_by_ext("directory",".ext")
def return_file_list_by_ext(directory,ext):
    import os
    file_list = []
    for file in os.listdir(directory):
        if file.endswith(ext):
            # Store the Full Path
            file_list.append(os.path.join(directory, file))
    return file_list

Usage yourfilelist = return_file_list_by_ext(r”E:\Root\Corpus\Text\Cleaning\\”,”.txt”)

The command above will return in a list – the full path including filename in directory E:\Root\Corpus\Text\Cleaning\ that end with .txt.


Need a Creator Alchemist on Your Project?

I’m available for hire—consulting, systems design, embedded tech, creative problem-solving, or anything in between.

If you’ve got a project that needs someone who can think it through and build it out, I’m interested.


LET’S KEEP IN TOUCH!

Get notified when I post something new!

We don’t spam! Read our privacy policy for more info.


LET’S KEEP IN TOUCH!

Get notified when I post something new!

We don’t spam! Read our privacy policy for more info.

Pin It on Pinterest

Share This