获取指定文件夹中文件的函数,网上学习时东拼西凑的结果。
注意,其中文件名如1.txt,文件路径如D:文件夹1.txt;direct为第一层子级
import os #filePath 输入文件夹全路径 #mode # 1递归获取所有文件名; # 2递归获取所有文件路径; # 3获取direct文件名; # 4获取direct文件路径; # 5获取direct文件名和direct子文件夹名; # 6获取direct文件路径和direct子文件夹路径 def getFile(filePath, mode, type): listResult=[] if mode == 1: for parent, dirNames, fileNames in os.walk(rootdir): for fileName in fileNames: if type !="" and not fileName.endswith(type): continue listResult.append(fileName) elif mode == 2: for parent, dirNames, fileNames in os.walk(rootdir): for fileName in fileNames: if type !="" and not fileName.endswith(type): continue listResult.append(os.path.join(parent, fileName)) elif mode == 3: listFileTitle = os.listdir(filePath) for each in listFileTitle: eachFilePath = os.path.join(filePath, each) if os.path.isfile(eachFilePath): if(type !="" and not eachFilePath.endswith(type)): continue listResult.append(each) elif mode == 4: listFileTitle = os.listdir(filePath) for each in listFileTitle: eachFilePath = os.path.join(filePath, each) if os.path.isfile(eachFilePath): if type !="" and not eachFilePath.endswith(type): continue listResult.append(eachFilePath) elif mode == 5: listTemp=os.listdir(filePath) for each in listTemp: eachFilePath = os.path.join(filePath, each) if (os.path.isfile(eachFilePath) and type !="" and not eachFilePath.endswith(type)): continue #是文件#指定了后缀#不是指定的后缀 listResult.append(each) elif mode == 6: listFileTitle = os.listdir(filePath) for eachTitle in listFileTitle: eachFilePath=os.path.join(filePath, eachTitle) if (os.path.isfile(eachFilePath) and type !="" and not eachFilePath.endswith(type)): continue #是文件#指定了后缀#不是指定的后缀 listResult.append(eachFilePath) return listResult rootdir = "D:\Test" outPath = "D:\pyTest.txt" fileWriter = open(outPath, 'w') for each in range(1,7,1): fileWriter.write(' ') fileWriter.write("mode==") fileWriter.write(str(each)) fileWriter.write(' ') listFile=getFile(rootdir, each, '.PPT') for each in listFile: fileWriter.write(each+' ') fileWriter.close()
我喜欢在解决问题的同时,将解决方法封装并适应多种相似情况,以达到一劳永逸的效果。这样不仅可以得到一个小工具,而且后期遇到未考虑到的情况时,翻起原来整理的内容也理解的快。下面是获取指定文件夹中文件的函数,也是在网上学习时东拼西凑的结果。注意,其中文件名如1.txt,文件路径如D:文件夹1.txt;direct为第一层子级
建议自己码一遍,不想码?拿走别客气