zoukankan      html  css  js  c++  java
  • python的遍历模式

    python的遍历在程序中很重要,详细了解一下遍历模式,可以应用于任务分发,数据的读写中。

    python的 递归遍历目录:

    import os

    def getAllDirRE(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)
    #递归调用
    getAllDirRE(fileAbsPath, sp)
    else:
    print(sp + "普通文件:", fileName)

    getAllDirRE(r"C:UsersxlgDesktopPython-1704day09 empdir")


    python栈模拟递归遍历目录(深度遍历):
    import os

    def getAllDirDE(path):
    stack = []
    stack.append(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)
    #["B", "E", "F"]
    else:
    #打印普通文件
    print("普通:" + fileName)

    getAllDirDE(r"C:UsersxlgDesktopPython-1704day09 empdir")


    python的广度遍历目录(队列):
    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"C:UsersxlgDesktopPython-1704day09 empdir")
     
     
  • 相关阅读:
    MySQL性能优化的最佳20+条经验
    初窥Linux 之 我最常用的20条命令
    Java内存模型
    未能加载文件或程序集“System.Net.Http.Formatting, Version=4.0.0.0, Culture=n
    Nginx 负载均衡之 upstream 参数 和 location 参数
    Nginx 简单配置方法
    关于使用 autoFac 的注入方法
    关于 VS 调用存储过程加载很慢和SQL 执行很快的那些事
    C# 客户端读取共享目录文件
    NodeJS、NPM安装配置步骤
  • 原文地址:https://www.cnblogs.com/mumu1/p/12708277.html
Copyright © 2011-2022 走看看