python3实现文件夹的遍历,广度优先和深度优先

import os
path = 'C:\\Users\\Administrator\\Desktop\\test'

def depth_first(path):       # 深度优先遍历文件夹,栈,先进后出,先找到最深的,再弹出来,消耗内存
    for i in os.listdir(path):
        child = os.path.join(path, i)
        if os.path.isdir(child):
            depth_first(child)
        else:
            print(child)

# depth_first(path)

def breadth_first(path, file_list=[]):      # 广度优先遍历文件夹,list装文件夹,装一个弹出一个,不占有内存,队列先进先出
    file_list.append(path)
    while len(file_list) > 0:
        tmp = file_list.pop(0)
        for i in os.listdir(tmp):
            child = os.path.join(tmp, i)
            if os.path.isdir(child):
                print(child)
                file_list.append(child)
            else:
                print(child)

# breadth_first(path)

你可能感兴趣的:(python学习)