Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively searching for files with specific extensions in a directory

Tags:

python

For some reason this returns me an empty list, and I have no idea why.

import os, fnmatch

vidext = ['.avi', '.mkv', '.wmv', '.mp4', '.mpg', '.mpeg', '.mov', '.m4v']

def findExt(folder):
    matches = []
    for root, dirnames, filenames in os.walk(folder):
        for extension in vidext:
            for filename in fnmatch.filter(filenames, extension):
                matches.append(os.path.join(root, filename))
    return matches

print(findExt("D:\TVRip"))
like image 944
yaka Avatar asked Jan 10 '23 22:01

yaka


1 Answers

You'd need to add a wildcard to each extension for fnmatch.filter() to match:

fnmatch.filter(filenames, '*' + extension)

but there is no need to use fnmatch here at all. Just use str.endswith():

for root, dirnames, filenames in os.walk(folder):
    for filename in filenames:
        if filename.endswith(extensions):
            matches.append(os.path.join(root, filename))

or expressed as a list comprehension:

return [os.path.join(r, fn)
        for r, ds, fs in os.walk(folder) 
        for fn in fs if fn.endswith(extensions)]
like image 52
Martijn Pieters Avatar answered Feb 08 '23 05:02

Martijn Pieters