• 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")
     
     
  • 相关阅读:
    Filesystem Case-Sensitivity Mismatch
    内存分配
    单链表
    PHP校验日期格式是否合法
    Automatically populating $HTTP_RAW_POST_DATA is deprecated
    preg_match(): Compilation failed: character value in x{} or o{} is too large at offset 8
    CGI 和 FastCGI 协议的运行原理
    冒泡排序
    油猴子脚本-过滤百度广告
    查看chrome插件源码
  • 原文地址:https://www.cnblogs.com/mumu1/p/12708277.html
Copyright © 2020-2023  润新知