递归就是子程序(或函数)直接调用自己或通过一系列调用语句间接调用自己,是一种描述问题和解决问题的基本方法。

说白了递归就是函数自己玩自己

  
  1. def getAllDirAndFile(path, p=''):
  2. # 得到当前目录下所有的文件
  3. fileList = os.listdir(path)
  4. # print(fileList)
  5. p += " "
  6. # 处理每一个文件
  7. for fileName in fileList:
  8. # isdir isfile
  9. # 获取文件或文件夹的绝对路径
  10. fileAbs = os.path.join(path, fileName)
  11. # print(fileAbs)
  12. # 判断当前路径是不是文件夹
  13. if os.path.isdir(fileAbs):
  14. print(p + '文件夹' + fileName)
  15. # 递归调用
  16. getAllDirAndFile(fileAbs, p)
  17. else:
  18. print(p + '普通文件' + fileName)

使用栈遍历目录又叫深度遍历(不撞南墙不回头,然后再去走另一条路)

想象一摞被堆起来的书,这就是栈。这堆书的特点是,最后被堆进去的书,永远在最上面。从这堆书里面取一本书出来,取哪本书最方便?肯定是最上面那本。栈这种数据结构的特点就是如此:后进先出(Last In First Out - LIFO),即最后被堆进去的数据,最先被拿出来

  
  1. def getAllDirAndFile(path):
  2. stack = [] # 空元素
  3. stack.append(path) # [r'C:\Users\xlg\Desktop\a']
  4. # 循环遍历处理栈的内容,当栈里面的内容为空时退出
  5. while len(stack) != 0:
  6. # 从栈里取出元素
  7. dirPath = stack.pop()
  8. # 遍历dirPath目录下的所有文件
  9. fileList = os.listdir(dirPath)
  10. for fileName in fileList:
  11. fileAbs = os.path.join(dirPath, fileName)
  12. if os.path.isdir(fileAbs):
  13. # 当当前目录时文件夹,进行入栈操作
  14. print( '文件夹' + fileName)
  15. stack.append(fileAbs)
  16. else:
  17. print( '普通文件' + fileName)

使用队列遍历目录又叫做广度遍历(所有的路一起走)

队列是一种列表,不同的是队列只能在队尾插入元素,在队首删除元素。队列用于存

储按顺序排列的数据,先进先出,这点和栈刚好相反

  
  1. def getAllDirAndFile(path):
  2. # 创建队列
  3. queue = collections.deque()
  4. # 添加元素
  5. queue.append(path) #[a]
  6. while len(queue) != 0:
  7. # 移除队列中的元素
  8. dirPath = queue.popleft()
  9. # 获取dirPath下的所有文件及文件夹
  10. fileList = os.listdir(dirPath)
  11. for fileName in fileList:
  12. # 绝对路径
  13. fileAbs = os.path.join(dirPath, fileName)
  14. # 如果是文件夹就放到队列中
  15. if os.path.isdir(fileAbs):
  16. print( '文件夹' + fileName)
  17. queue.append(fileAbs)
  18. else:
  19. print( '文件' + fileName)