python 获取目录结构
目的: 按照某个基准目录展示分层。实现文件分层展示,可以控制层级。可以控制是否需要打印文件。
主要点
- 构建树。采取path_tree 结构构建,没有明显区分root和子树的概念因为结构都是一致的。
- 设置level。因为这个结构可以理解为单向的链表树。增加level存储,用于展示的时候分层。
- 层次遍历树结构。标准用法是使用stack结构。但是python似乎没有标准的stack库,使用LifoQueue 代替实现。
import sys
import os
from queue import LifoQueue
class PathTree:
def __init__(self, name, level):
self.name = name
self.level = level
self.sub_list = []
def add_sub(self, sub_name):
self.sub_list.append(sub_name)
def get_path(path, path_tree, is_need_file=False, max_level=1):
print is_need_file
if path_tree.level == max_level:
return
if os.path.isdir(path):
for current_dir in os.listdir(path):
full_path = os