Get Files in a Directory By Extension in Python 3

The os.listdir method helps us to list directory contents. The fnmatch.fnmatch method helps us find files that are named a certain way (e.g. have a certain extension).

Here is a function that returns a list of .txt files in a directory:

import fnmatch
import os

def get_files_by_ext(dirpath, ext):
    files = []
    for file in os.listdir(dirpath):
        if fnmatch.fnmatch(file, '*.' + ext):
            files.append(os.path.join(dirpath, file).replace("\", "/"))
    return files

text_files = get_files_by_ext('c:/myfiles', 'txt')
print(','.join(text_files))

The output is:

c:/myfiles/a.txt,c:/myfiles/b.txt,c:/myfiles/c.TXT

with c:/myfiles as follows:

a windows explorer dialog showing some files

Note that the fnmatch function is not case sensitive (it matches .txt and .TXT)

Comments

Leave a comment

What color are green eyes? (spam prevention)
Submit
Code under MIT License unless otherwise indicated.
© 2020, Downranked, LLC.