python walk/递归/深度/广度遍历

import collections
import os

#目录遍历
class DirTraverse:
    def __init__(self):
        self.queue = collections.deque()

    #1.walk遍历
    def traverse_by_walk(self,path):
        #absolutePath  当前目录的绝对路径
        #childPath 当前目录的子目录  列表
        #当前目录中文件 列表
        for absolutePath,childPath,files in os.walk(path):
            # print(absolutePath,childPath,files)
            # print(files)
            for file in files:
                print(file)

    #2.递归遍历
    def traverse_by_recurise(self,path):
        if not os.path.isdir(path):  #如果不是目录,直接返回
            return
        all_items = os.listdir(path)  #得到当前目录下的所有文件及子目录
        for item in all_items:
            abs_path = os.path.join(path,item)
            if os.path.isdir(abs_path): #如果是目录
                self.traverse_by_recurise(abs_path)  #递归遍历
            else:
                print(item)   #如果是文件,直接输出

    #3. 广度优先遍历,按层遍历  了解
    def traverse_by_brand(self,path):
        self.queue.append(path)  #先入队
        while len(self.queue) > 0:
            item = self.queue.popleft()  #左边出队
            childs = os.listdir(item)  #获取所有的项目(目录,文件)
            for current in childs:
                abs_path = os.path.join(item,current)  #绝对路径
                if os.path.isdir(abs_path):  #如果是目录,则入队
                    self.queue.append(abs_path)
                else:
                    print(current)  #输出
    #4.深度优先遍历  了解
    def traverse_by_depth(self,path):
        self.queue.append(path) #入栈
        while len(self.queue) != 0:
            top = self.queue.pop()  #右边出队,栈
            all_items = os.listdir(top)
            for item in all_items:
                abs_path = os.path.join(top,item)
                if os.path.isdir(abs_path):
                    self.queue.append(abs_path)
                else:
                    print(item)


d1 = DirTraverse()
# d1.traverse_by_walk(r"C:\course\python\15")
# d1.traverse_by_recurise(r"C:\course\python\15")
# d1.traverse_by_brand(r"C:\course\python\15")
"""
15_文件和目录.md
广度遍历.png
深度遍历.png
a.png
1_os.py
2_dirtraverse.py
homework11.py
review.py
b.png
c.png
"""
d1.traverse_by_depth(r"C:\course\python\15")
"""
15_文件和目录.md
广度遍历.png
深度遍历.png
1_os.py
2_dirtraverse.py
homework11.py
review.py
a.png
b.png
c.png

"""

猜你喜欢

转载自blog.csdn.net/weixin_42218889/article/details/81483640