本文共 1623 字,大约阅读时间需要 5 分钟。
用递归方法遍历目录:
使用到os模块,所以要先引入os模块
处理文件:
核心是判断文件是否是目录文件,如果是目录文件就进行递归处理,直接将文件名打印出来
下面是文件代码:
import osdef getAllDir(path, sp = " "): fileList = os.listdir(path) #处理每一个文件 sp += " " for fileName in fileList: #判断是否是路径(用绝对路径) absFliePath = os.path.join(path, fileName) if os.path.isdir(absFliePath): print(sp + "目录:", fileName) #递归调用 getAllDir(absFliePath, sp) else: print(sp + "普通文件", fileName) return fileListgetAllDir(r"C:\Users\Administrator\PycharmProjects\untitled\day011")
栈方法:
import osdef getAllDirDE(path): stack = [] stack.append(path) #处理栈,当栈为空的时候结束循环 while len(stack) != 0: dirPath = stack.pop() fileDir = os.listdir(dirPath) for fileName in fileDir: fileAbsPath = os.path.join(dirPath, fileName) if os.path.isdir(fileAbsPath): print("目录:"+ fileName) stack.append(fileAbsPath) else: print("普通文件:", fileName)getAllDirDE(r"C:\Users\Administrator\PycharmProjects\untitled\day011")队列方法:
import osimport collectionsdef getAllDir(path): queue = collections.deque() #进队 queue.append(path) while len(queue) != 0: dirPath = queue.popleft() fileList = os.listdir(dirPath) for fileName in fileList: fileAbsPath = os.path.join(dirPath, fileName) if os.path.isdir(fileAbsPath): print("目录:"+fileName) queue.append(fileAbsPath) else: print("文件:"+fileName)getAllDir(r"C:\Users\Administrator\PycharmProjects\untitled\day011")
转载地址:http://yhixa.baihongyu.com/