递归就是子程序(或函数)直接调用自己或通过一系列调用语句间接调用自己,是一种描述问题和解决问题的基本方法。
说白了递归就是函数自己玩自己
-
def getAllDirAndFile(path, p=''):
-
# 得到当前目录下所有的文件
-
fileList = os.listdir(path)
-
# print(fileList)
-
p +=
" "
-
# 处理每一个文件
-
for fileName
in fileList:
-
# isdir isfile
-
# 获取文件或文件夹的绝对路径
-
fileAbs = os.path.join(path, fileName)
-
# print(fileAbs)
-
# 判断当前路径是不是文件夹
-
if os.path.isdir(fileAbs):
-
print(p +
'文件夹' + fileName)
-
# 递归调用
-
getAllDirAndFile(fileAbs, p)
-
else:
-
print(p +
'普通文件' + fileName)
使用栈遍历目录又叫深度遍历(不撞南墙不回头,然后再去走另一条路)
想象一摞被堆起来的书,这就是栈。这堆书的特点是,最后被堆进去的书,永远在最上面。从这堆书里面取一本书出来,取哪本书最方便?肯定是最上面那本。栈这种数据结构的特点就是如此:后进先出(Last In First Out - LIFO),即最后被堆进去的数据,最先被拿出来
-
def getAllDirAndFile(path):
-
stack = []
# 空元素
-
stack.append(path)
# [r'C:\Users\xlg\Desktop\a']
-
# 循环遍历处理栈的内容,当栈里面的内容为空时退出
-
while len(stack) !=
0:
-
# 从栈里取出元素
-
dirPath = stack.pop()
-
# 遍历dirPath目录下的所有文件
-
fileList = os.listdir(dirPath)
-
for fileName
in fileList:
-
fileAbs = os.path.join(dirPath, fileName)
-
if os.path.isdir(fileAbs):
-
# 当当前目录时文件夹,进行入栈操作
-
print(
'文件夹' + fileName)
-
stack.append(fileAbs)
-
else:
-
print(
'普通文件' + fileName)
使用队列遍历目录又叫做广度遍历(所有的路一起走)
队列是一种列表,不同的是队列只能在队尾插入元素,在队首删除元素。队列用于存
储按顺序排列的数据,先进先出,这点和栈刚好相反
-
def getAllDirAndFile(path):
-
# 创建队列
-
queue = collections.deque()
-
# 添加元素
-
queue.append(path)
#[a]
-
while len(queue) !=
0:
-
# 移除队列中的元素
-
dirPath = queue.popleft()
-
# 获取dirPath下的所有文件及文件夹
-
fileList = os.listdir(dirPath)
-
for fileName
in fileList:
-
# 绝对路径
-
fileAbs = os.path.join(dirPath, fileName)
-
# 如果是文件夹就放到队列中
-
if os.path.isdir(fileAbs):
-
print(
'文件夹' + fileName)
-
queue.append(fileAbs)
-
else:
-
print(
'文件' + fileName)