遍历目录下的文件

最近想着遍历目录下面得所有文件,兜兜转转回到了最初想要的效果
为啥遍历目录? 主要还是为了实现动态导入库和自动生成API,特意记录下来这个方法

#以下是采用二叉树的概念进行实现
import os

class Node:
    def __init__(self,path):
        self.path = path
        self.profile = []
        self.file = []


class Tree:
    def __init__(self):
        self.root = None

    def showpath(self,nodevalue):
        if self.root is None:
            self.root = Node(nodevalue)

        store_path = {}
        queue = [self.root]
        while queue:
            node = queue.pop(0)
            for file in os.listdir(node.path):
                newpath = os.path.join(node.path,file)
                if os.path.isdir(newpath):
                    newnode = Node(newpath)
                    node.profile.append(newnode)
                    queue.append(newnode)
                else:
                    node.file.append(newpath)


        requeue = [self.root]
        allfile = []
        while requeue:
            node = requeue.pop(0)
            if node.profile:
                requeue.extend([i for i in node.profile])
            if node.file:
                store_path[node.path] = node.file
        for i in store_path.values():
            allfile = allfile + i
        return allfile
#以下是最初想要的效果,目录组成一个字典,目录下包含文件元素

def deepfile(path,store_path={}):

    if not os.path.isdir(path):
        return

    store_path[path] = []
    dirfile = os.listdir(path)
    for file in dirfile:
        nextpath = os.path.join(path,file)
        if os.path.isdir(nextpath):
            if len(store_path[path]) > 0:
                if not isinstance(store_path[path][0], dict):
                    store_path[path].insert(0, {})

            elif len(store_path[path]) == 0:
                store_path[path].insert(0, {})

            deepfile(nextpath,store_path[path][0])
        else:
            store_path[path].append(nextpath)

    return store_path

# 得到得效果和二叉树有点类似
def deepfile(filepath):

    if not os.path.isdir(filepath):
        return

    store_path = {}

    queue = [filepath]
    while queue:
        path = queue.pop(0)
        lsdir = os.listdir(path)
        store_path[path] = []
        for file in lsdir:
            nextpath = os.path.join(path,file)
            if os.path.isdir(nextpath):
                queue.append(nextpath)
            else:
                store_path[path].append(nextpath)

    return store_path


版权声明:本文为weixin_41597669原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。