Recursively searching for files with specific extensions in a directory

后端 未结 1 1966
庸人自扰
庸人自扰 2021-01-21 05:25

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\',         


        
相关标签:
1条回答
  • 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)]
    
    0 讨论(0)
提交回复
热议问题