美文网首页
递归,栈,队列遍历目录

递归,栈,队列遍历目录

作者: 四十是似时 | 来源:发表于2018-03-04 14:42 被阅读0次

本文来自我的博客


递归 遍历目录

思路:

1. 定义函数,参数值为需要遍历的路径

2. 运用内置函数listdir ,将获取到的路径拆分成列表

3. 循环遍历列表

4. 拼接路径,用于判断是否是目录还是文件

5. 如果是目录:

      递归调用自己

6. 如果是文件:

      打印

7. 找到函数出口: 如果目录不存在,则return

[python] view plain copy

def getDir(sourcePath):  

if not os.path.exists(sourcePath):  

return  

    listDir = os.listdir(sourcePath)  

for fileName in listDir:  

        absPath = os.path.join(sourcePath,fileName)  

if os.path.isfile(absPath):  

print(absPath)  

if os.path.isdir(absPath):  

print(absPath)  

            getDir(absPath)  

if __name__ == '__main__':  

path = r"D:\aa\aaa\aa\aa\"  

    getDir(path)  

队列 遍历目录

思路:

1.定义函数,参数值为需要遍历的路径

2.创建列表

3.将第一个路径放入其中

4.需要循环执行,放入与删除的操作,取出列表中放入的第一个值

5.使用listdir 将该路径下的所有文件与目录封装成列表,且循环遍历他

6.将遍历出来的元素,与原路径拼接起来

7.判断是目录还是文件: 如果是目录,则将其添加至队列

                    如果是文件,则打印

8.找到出口为当所有目录都已遍历完,not exist 则return

9.判断第一个循环的出口为当队列中已经没有了任何元素即len()==0,则break

[python] view plain copy

import collections  

def getDir(sourcePath):  

if not os.path.exists(sourcePath):  

return  

    queue = collections.deque()  

    queue.append(sourcePath)  

while True:  

if len(queue)==0:  

break  

        path = queue.popleft()    

for fileName in os.listdir(path):  

            absPath = os.path.join(path,fileName)  

if os.path.isdir(absPath):  

print(absPath)  

                queue.append(absPath)  

if os.path.isfile(absPath):  

print(absPath)  

if __name__ == '__main__':  

path = r"D:\sss\sssd\ddd"  

    getDir(path)  

栈 遍历目录

[python] view plain copy

def getDir(sourcePath):  

if not os.path.exists(sourcePath):  

return  

    stack = []  

    stack.append(sourcePath)  

while True:  

if len(queue)==0:  

break  

        path = stack.pop  

for fileName in os.listdir(path):  

            absPath = os.path.join(path,fileName)  

if os.path.isdir(absPath):  

print(absPath)  

                stack.append(absPath)  

if os.path.isfile(absPath):  

print(absPath)  

if __name__ == '__main__':  

path = r"D:\aaa\aa\aa"  

    getDir(path)  

相关文章

网友评论

      本文标题:递归,栈,队列遍历目录

      本文链接:https://www.haomeiwen.com/subject/aloffftx.html