用递归方法遍历目录:
使用到os模块,所以要先引入os模块
处理文件:
核心是判断文件是否是目录文件,如果是目录文件就进行递归处理,直接将文件名打印出来
下面是文件代码:
import os
def 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 fileList
getAllDir(r"C:\Users\Administrator\PycharmProjects\untitled\day011")
栈方法:
import os
def 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 os
import collections
def 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")