1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
|
import os as os import re as re
try: import typing as typing except: pass
class FilePathProcessor(object): u"""用于处理文件的类"""
@classmethod def CheckIfDirExist (cls, dirPath): u"""判断文件夹是否存在, 否则抛出异常""" if not os.path.exists(dirPath): raise Exception(u"不存在文件夹, 或不是文件夹 : {}".format(dirPath))
@classmethod def GetAllFileWithExt (cls, dirPath, extFormat, bSingleDir=True): u"""遍历文件夹以寻找特定格式的文件"""
cls.CheckIfDirExist (dirPath) lowerExtFormat = extFormat.lower() if bSingleDir: for fileName in os.listdir(dirPath): tempFilePath = os.path.join(dirPath,fileName) if (not os.path.isdir(tempFilePath)) and (fileName.lower().endswith(lowerExtFormat)): yield tempFilePath else : for dirPath,dirNames,fileNames in os.walk(dirPath): for fileName in fileNames: if fileName.lower().endswith(lowerExtFormat): yield os.path.join(dirPath, fileName)
@classmethod def GetAllFileRegexWithExt (cls, dirPath, extFormat, bSingleDir=True, bUseRegex=False, regexRule=""): u"""遍历文件夹以寻找特定格式的文件, 且可选是否包含特定的Regex"""
pathGenerator = cls.GetAllFileWithExt(dirPath,extFormat,bSingleDir) if not bUseRegex: for filePath in pathGenerator: yield filePath else : regexMatchRule = re.compile(regexRule,re.I) for filePath in pathGenerator: regexMatched = regexMatchRule.search(os.path.basename(filePath)) if regexMatched != None : yield filePath
if __name__ == "__main__": targetDirPath = os.environ["userprofile"] targetExtFormat = ".fbx" bUseSingleDir = False bUseRegex = True regexRule = r"^anim.*?" filePathGenerator = FilePathProcessor.GetAllFileRegexWithExt( targetDirPath, targetExtFormat, bUseSingleDir, bUseRegex, regexRule)
for filePath in filePathGenerator : print(filePath)
|