Python笔记_第二篇_面向过程_第二部分_4.常用模块的简单使用_操作系统模块(os)和队列模块(collections)

1. 用递归函数遍历目录:

import os

def getAllDir(path,sp=" "):
    # 得到当前目录下所有的文件
    filesList = os.listdir(path)
    # 处理每一个文件
    sp += "  "
    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"G:\博易大师5五档行情-中信建投期货(CTP主席)")

 

2. 栈模拟递归遍历目录(深度遍历)

import os

def getAllDirDE(path):
    stack = []
    stack.append(path) # 压栈内容:G:\博易大师5五档行情-中信建投期货(CTP主席)
    # print(path)

    while len(stack) != 0: # 处理栈,当栈为空的时候结束循环
        # 从栈里取出数据(取出的是上面那个路径)
        dirPath = stack.pop()
        # print(dirPath)
        filesList = os.listdir(dirPath) # 把弹栈的那个目录拿出来
        # print(filesList) # 观察应该是绝对路径
        for fileName in filesList: # 得到目录下每一个文件(有可能是文件,有可能是目录)
            # 处理如果每一个文件,如果是普通文件则打印出来,如果是目录就讲该路径
            # 再压入栈内。
            fileAbsPath = os.path.join(dirPath,fileName)
            if os.path.isdir(fileAbsPath):
                # 如果是目录打印并压栈
                print("目录:" , fileName)
                stack.append(fileAbsPath)
            else:
                # 如果是文件就打印目录
                print(" 文件:",fileName)

getAllDirDE(r"G:\博易大师5五档行情-中信建投期货(CTP主席)")

 

3. 队列模拟递归遍历目录(广度遍历)

import os
import collections

def getAllDirQU(path):
    # 初始空队列
    queue = collections.deque()
    # 进队列
    queue.append(path)

    while len(queue) != 0:
        # 出队数据
        dirPath = queue.popleft()
        # 找出所有文件
        filesList = os.listdir(dirPath)

        for fileName in filesList:
            # 绝对路径
            fileAbsPath = os.path.join(dirPath,fileName)
            # 判断是否是目录,是目录就进队,不是就打印
            if os.path.isdir(fileAbsPath):
                print("目录: " + fileName)
                queue.append(fileAbsPath)
            else:
                print(" 普通文件:" + fileName)

getAllDirQU(r"G:\博易大师5五档行情-中信建投期货(CTP主席)")

 

4. 备注:深度遍历和广度遍历

  4.1 深度遍历(depthFirstSearch - DFS)

    由起始点起始点开始,沿着一条道路一直走,当走到走不动的时候,再回来走一条可以走的通的道路,然后再继续往下走,知道走不到,再回来。

  4.2 广度遍历(broadFirstSearch - BFS)

    广度遍历是按照层来进行处理定点,举例开始点最近的那些点首先被访问,而最远的那些定点则最后被访问。

  我们通过图示来进行讲解会更加的直观:

  

 

  

 

posted @ 2019-05-12 19:36  时海涛|Thomas  阅读(229)  评论(0编辑  收藏  举报