python学习 生成目录树

第一种最速方式,cmd直接用tree命令,如果还要文件用 tree /f

C:\Users\ds>tree d:\9月考勤 > d:\test.xls

C:\Users\ds>tree /f  d:\9月考勤 > d:\test.xls

第二种,注意要管理员权限(即可以进入所有要生成的目录),可以按需生成目录树或文件树:

警告:这个是遍历的,如果目录太大会超级慢,可以自行用os.walk 结合level 修改成遍历文件夹

import time
import os
import subprocess as sp

    def list_files(startPath):

    #目录输出的文件
     with open(r'd:\list.txt', 'w') as fileSave:
    #遍历目录
        for root, dirs, files in os.walk(startPath):
    #设置遍历层级
            level = root.replace(startPath, '').count(os.sep)
    #根据层级设定目录输出范围,不需要可以注释掉
            if level<=2:
                indent = '*' * 1 * level
    #输出目录名
                fileSave.write('{}{}'.format(indent, os.path.basename(root)) + '\n')
    #输出完整目录名带路径
            #fileSave.write('{}{}\\'.format(indent, os.path.abspath(root)) + '\n')
    #下面同上,主要是输出文件用
            #subIndent = '*' * 1 * (level + 1)

            #for f in files:

                # fileSave.write('{}{}'.format(subIndent, f) + '\n')

                #fileSave.write('{}{}{}'.format(subIndent, os.path.abspath(root), f) + '\n')

        fileSave.close()


if __name__ == '__main__':


    path= r'd:\共享'
    #dir = raw_input('please input the path:')

    list_files(path)

第三种(这个是转的,出处忘了):

import os
import subprocess as sp

import re
from pathlib import Path
from pathlib import WindowsPath
from typing import Optional, List

class DirectionTree:
    def __init__(self,
                 direction_name: str = 'WorkingDirection',
                 direction_path: str = '.',
                 ignore_list: Optional[List[str]] = None):
        self.owner: WindowsPath = Path(direction_path)
        self.tree: str = direction_name + '/\n'
        self.ignore_list = ignore_list
        if ignore_list is None:
            self.ignore_list = []
        self.direction_ergodic(path_object=self.owner, n=0)
    def abc(self):
        print(self)

    def tree_add(self, path_object: WindowsPath, n=0, last=False):
        if n > 0:
            if last:
                self.tree += '│' + ('    │' * (n - 1)) + '    └────' + path_object.name
            else:
                self.tree += '│' + ('    │' * (n - 1)) + '    ├────' + path_object.name
        else:
            if last:
                self.tree += '└' + ('──' * 2) + path_object.name
            else:
                self.tree += '├' + ('──' * 2) + path_object.name
        if path_object.is_file():
            self.tree += '\n'
            return False
        elif path_object.is_dir():
            self.tree += '/\n'
            return True

    def filter_file(self, file):
        for item in self.ignore_list:
            if re.fullmatch(item, file.name):
                return False
        return True

    def direction_ergodic(self, path_object: WindowsPath, n=0):
        dir_file: list = list(path_object.iterdir())
        dir_file.sort(key=lambda x: x.name.lower())
        dir_file = [f for f in filter(self.filter_file, dir_file)]
        for i, item in enumerate(dir_file):
            if i + 1 == len(dir_file):
                if self.tree_add(item, n, last=True):
                    self.direction_ergodic(item, n + 1)
            else:
                if self.tree_add(item, n, last=False):
                    self.direction_ergodic(item, n + 1)


if __name__ == '__main__':
    i_l = [
        '\.git', '__pycache__', 'test.+', 'venv', '.+\.whl', '\.idea', '.+\.jpg', '.+\.png',
        'image', 'css', 'admin', 'tool.py', 'db.sqlite3'
    ]
    tree = DirectionTree(ignore_list=i_l, direction_path=r'D:\9月')
    print(tree.tree)

再来一种,转:Python实战笔记(一) 递归输出目录结构 - 半虹 - 博客园

你可能感兴趣的:(python)