遍历文件夹内所有子文件夹和文件并创建多叉树结构
遍历文件夹内所有子文件夹和文件并创建多叉树结构
第一次分享自己所学的内容,欢迎大家交流。最近由于需要提取一个文件夹中的所有图片,因此需要遍历文件夹,从网上的代码基本也能够完成遍历搜索,但是没有保存其搜索时的多叉树的结构,因此分享一下自己代码。
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前言
第一次分享自己所学的内容,欢迎大家交流。最近由于需要提取一个文件夹中的所有图片,因此需要遍历文件夹,从网上的代码基本也能够完成遍历搜索,但是没有保存其搜索时的多叉树的结构,因此分享一下自己代码。
代码
代码如下:
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,各个节点
总结
总体来说实现了遍历搜索所有子文件夹和子文件,并且按照多叉树的节点位置进行了分别的保存。