您现在的位置是:首页 > 文章详情

Python零基础学习笔记(三十八)—— 递归方法、栈、队列模拟遍历目录

日期:2019-01-25点击:523

用递归方法遍历目录:

使用到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")

原文链接:https://yq.aliyun.com/articles/689020
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章