2021-09-26

遍历文件夹内所有子文件夹和文件并创建多叉树结构

遍历文件夹内所有子文件夹和文件并创建多叉树结构

第一次分享自己所学的内容,欢迎大家交流。最近由于需要提取一个文件夹中的所有图片,因此需要遍历文件夹,从网上的代码基本也能够完成遍历搜索,但是没有保存其搜索时的多叉树的结构,因此分享一下自己代码。
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

第一次分享自己所学的内容,欢迎大家交流。最近由于需要提取一个文件夹中的所有图片,因此需要遍历文件夹,从网上的代码基本也能够完成遍历搜索,但是没有保存其搜索时的多叉树的结构,因此分享一下自己代码。

代码

代码如下:

import os
def file_tree(dir_name, node_father, location, dir_list, file_list, node_list):
    # dir_name: 文件路径
    # node_father: 父节点, 第一个元素代表树的深度,第二个代表当前深度下的索引
    # location: 当前节点, 第一个元素代表树的深度,第二个代表当前深度下的索引
    # dir_list: 遍历得到的文件夹列表
    # file_list: 非文件夹的文件路径列表
    # node_list: 节点列表
    node = []
    # node: 节点,内容为[节点名(路径),父节点, 当前节点]
    node_append = node.append
    node_append(dir_name)
    node_append(node_father)
    node_append(location)
    node_append = node_list.append
    node_append(node)
    if os.path.isdir(dir_name):
        dir_append = dir_list.append
        dir_append(dir_name)
        for file_index, file_path in enumerate(os.listdir(dir_name)):
                # 若子节点是文件夹,则进一步进行搜索,进入递归搜索模式
                sub_location = (location[0] + 1, file_index)
                file_tree(os.path.join(dir_name, file_path), location, sub_location, dir_list, file_list, node_list)
    else:
        file_append = file_list.append
        file_append(dir_name)
        print(dir_name)
    return dir_list, file_list, node_list

if __name__=='__main__':
    root_path = 'E:\吴桓\筛孔识别\\2021-9-25'
    # 起始文件夹位置
    dir_list, file_list, node_list = file_tree(root_path, [0, 0], [0, 0], [], [], [])
    # 初始条件下,所有的列表均设为空

结果

结果如下:
在这里插入图片描述dir_list,文件夹列表

file_list,非文件夹列表
在这里插入图片描述
node_list,各个节点

总结

总体来说实现了遍历搜索所有子文件夹和子文件,并且按照多叉树的节点位置进行了分别的保存。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值