1.小功能
1. 某目录下所有x类型的文件,包括子目录下的
(1) 递归的
def getAllFiles(rootPath, allFiles, fileTypes): files = os.listdir(rootPath) for file in files: pathTmp = os.path.join(rootPath, file) # rootPath+'/'+file if (os.path.isfile(pathTmp) and pathTmp in fileTypes): allFiles.append(pathTmp) elif os.path.isdir(pathTmp): # is a dir getAllFiles(pathTmp, allFiles, fileTypes) return allFiles allFiles = [] fileTypes = ['jpg','png'] getAllFiles(r'xx/xx/xx',allFiles,fileTypes)
(2) os.walk
def allFilePathInDir(dir, fileTypes): pathLists = [] if not os.path.exists(dir): dir = os.getcwd() else: dir = os.path.abspath(dir) logging.debug('base dir:' + str(dir)) for folderName, subFolders, fileNames in os.walk(baseDir): for f in fileNames: fsplits = f.split('.') filetype = fsplits[len(fsplits) - 1] if filetype in fileTypes: pathLists.append(os.path.join(folderName, f)) return pathLists