递归搜索目录中具有特定扩展名的文件

时间:2014-03-28 13:19:06

标签: python

出于某种原因,这会给我一个空列表,我不知道为什么。

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"))

1 个答案:

答案 0 :(得分:10)

您需要为fnmatch.filter()的每个扩展名添加通配符以匹配:

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

但根本不需要使用fnmatch。只需使用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))

或表达为列表理解:

return [os.path.join(r, fn)
        for r, ds, fs in os.walk(folder) 
        for fn in fs if fn.endswith(extensions)]