python で 拡張子指定してファイル一覧検索
pythonで拡張子を指定して特定のフォルダ以下のファイルを検索する方法。
ポイント:
・拡張子を複数指定可能(大文字/小文字を自由に区別)
・複数のパスを同時に指定可能
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import glob from functools import reduce from itertools import chain def searchFiles(pathes:list, exts:list) -> list: """ searchFiles in pathes with target extention. Ex) searchFiles(["/mnt/media1", "/mnt/usb/**/music], ["*.mp3", "*.jpg"]) case of extension is ignored. return list of file path """ targetExts = [''.join(map(lambda c: '[%s%s]' % ( c.lower(), c.upper()) if c.isalpha() else c, ext)) for ext in exts] targetPathes = [ dirPath + "/" + ext for dirPath in pathes for ext in targetExts] foundFiles = map(lambda x: glob.iglob(x, recursive=True), targetPathes) foundFiles = reduce(lambda a, b: chain(a, b), foundFiles) # Flatten return foundFiles |
コメントを残す