python 遍历文件夹

一. 用递归遍历目录

# 定义一个函数来遍历目录
import os
def getAllDirAndFile(pathDir):
    # 判断是否是目录
    if not os.path.isdir(pathDir):
        return
    listNames = os.listdir(pathDir)
    for name in listNames:
        # 拼接成绝对路径
        absPath = os.path.join(pathDir,name)
        # 判断是否是目录
        if os.path.isdir(absPath):
            print("目录:%s"%(absPath))
            # 调用自己
            getAllDirAndFile(absPath)
        if os.path.isfile(absPath):
            print("文件:%s"%(absPath))

# 测试
getAllDirAndFile(path)

二. 栈实现深度遍历

import os
import collections
def getAllDirAndFile(pathDir):
    if not os.path.isdir(pathDir):
        return
    #创建一个栈
    strack = collections.deque()

    #把根路径放到队列中去
    strack.append(pathDir)

    while True:
        # 如果队列的长度为0, 则队列中已经没有数据.  不在遍历了
        if len(strack) == 0:
            break

        #把路径取出来遍历
        path = strack.pop()

        listNames = os.listdir(path)
        for name in listNames:
            absPath = os.path.join(path,name)
            if os.path.isfile(absPath):#文件
                print("文件:%s"%(absPath))
            if os.path.isdir(absPath):#目录
                print("目录:%s"%(absPath))
    #           将目录放入到队列中去
                strack.append(absPath)

# 测试:
path = r"C:\Users\Administrator\Desktop"
getAllDirAndFile(path)

3. 队列实现广度遍历

import  os
import collections
def getAllDirAndFile(pathDir):
    if not os.path.isdir(pathDir):
        return
    # 创建一个队列
    queue = collections.deque()

    # 把根路径放到队列中去
    queue.append(pathDir)

    while True:
        if len(queue) == 0:
            break

        # 把路径取出来遍历
        path = queue.popleft()

        listNames = os.listdir(path)
        for name in listNames:
            absPath = os.path.join(path, name)
            if os.path.isfile(absPath):
                print("文件:%s" % (absPath))
            if os.path.isdir(absPath):
                print("目录:%s" % (absPath))
                queue.append(absPath)

# 测试
getAllDirAndFile(r"F:\Program Files")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值