python基础学习16-遍历目录文件的几种写法(递归调用)

遍历目录文件的几种写法

整理为方便日后学习用到。

1. 简单递归

import os

def getAllDir(path, sp=""):
    sp += "   "
    filesList = os.listdir(path)
   # print(filesList)

    for fileName in filesList:
        fileAbsPath = os.path.join(path, fileName)
        if os.path.isdir(fileAbsPath):
            print(sp + "目录", fileName)
            getAllDir(fileAbsPath, sp)
        else:
            print(sp + "普通文件", fileName )

getAllDir(r"E:\file\python3")

2. 栈模拟(深度遍历)

定义栈 :stack = []
入栈 : stack.append()
出栈 : stack.pop()

import os

def getAllDirStack(path):
    stack = []
    #目录入栈
    stack.append(path)

    while len(stack) != 0: #栈不为空
        dirPath = stack.pop() #出栈
        filesList = os.listdir(dirPath) #获取目录下所有文件
        #处理每个文件,是目录则入栈,不是则打印。
        for fileName in filesList:
            fileAbsPath = os.path.join(dirPath, fileName)
            if os.path.isdir(fileAbsPath):
                stack.append(fileAbsPath)
                print("目录"+ fileName)
            else:
                print("普通文件", fileName )

getAllDirStack(r"E:\file\python3")

3. 队列模拟(广度遍历)

定义空队列:queue = collections.deque()
入队:queue.append()
出队:queue.popleft()

import os
import collections

def getAllDirQueue(path):
    queue = []
    queue.append(path)
    while len(queue) != 0:
        dirPath = queue.popleft()
        filesDir = os.listdir(dirPath)
        for fileName in filesDir:
            fileAbsPath = os.path.join(dirPath, fileName)
            if os.path.isdir(fileAbsPath):
                print("目录"+fileName)
                queue.append(fileAbsPath)
            else:
                print("普通文件"+fileName)

getAllDirQueue(r"E:\file\python3")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值