出于某种原因,这会给我一个空列表,我不知道为什么。
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"))
答案 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)]