• python树状打印项目路径


    学习这个的需求来自于,我想把项目架构告诉gpt问问它,然后不太会打印项目架构😂 联想到Linux的tree指令

    import os
    
    
    class DirectoryTree:
        def __init__(self, path):
            self.path = path
    
        def print_tree(self, method='default'):
            if method == 'default':
                self._print_dir_tree(self.path)
            elif method == 'with_count':
                self._print_dir_tree_with_count(self.path)
            elif method == 'files_only':
                self._print_files_only(self.path)
            elif method == 'with_symbols':
                self._print_dir_tree_with_symbols(self.path)
            else:
                print("Invalid method!")
    
        def _print_dir_tree(self, path, indent=0):
            print(' ' * indent + '|---' + os.path.basename(path))
            for item in os.listdir(path):
                itempath = os.path.join(path, item)
                if os.path.isdir(itempath):
                    self._print_dir_tree(itempath, indent + 2)
                else:
                    print(' ' * (indent + 2) + '|---' + item)
    
        def _print_dir_tree_with_count(self, path, indent=0):
            print(' ' * indent + '|---' + os.path.basename(path), end=' ')
            items = os.listdir(path)
            dirs = sum(1 for item in items if os.path.isdir(
                os.path.join(path, item)))
            files = len(items) - dirs
            print(f"(dirs: {dirs}, files: {files})")
            for item in items:
                itempath = os.path.join(path, item)
                if os.path.isdir(itempath):
                    self._print_dir_tree_with_count(itempath, indent + 2)
                else:
                    print(' ' * (indent + 2) + '|---' + item)
    
        def _print_files_only(self, path, indent=0):
            for item in os.listdir(path):
                itempath = os.path.join(path, item)
                if os.path.isdir(itempath):
                    self._print_files_only(itempath, indent)
                else:
                    print(' ' * indent + '|---' + item)
    
        def _print_dir_tree_with_symbols(self, path, indent=0):
            print(' ' * indent + '📁 ' + os.path.basename(path))
            for item in os.listdir(path):
                itempath = os.path.join(path, item)
                if os.path.isdir(itempath):
                    self._print_dir_tree_with_symbols(itempath, indent + 2)
                else:
                    print(' ' * indent + '📄 ' + item)
    
    
    
    
    class EnhancedDirectoryTree:
        def __init__(self, path):
            self.path = path
            self.show_hidden = False
            self.depth_limit = None
            self.show_files = True
            self.show_dirs = True
    
        def display_settings(self, show_hidden=False, depth_limit=None, 
                             show_files=True, show_dirs=True):
            self.show_hidden = show_hidden
            self.depth_limit = depth_limit
            self.show_files = show_files
            self.show_dirs = show_dirs
    
        def print_tree(self):
            self._print_dir(self.path)
    
        def _print_dir(self, path, indent=0, depth=0):
            if self.depth_limit is not None and depth > self.depth_limit:
                return
    
            if self.show_dirs:
                print(' ' * indent + '📁 ' + os.path.basename(path))
    
            for item in sorted(os.listdir(path)):
                # Check for hidden files/folders
                if not self.show_hidden and item.startswith('.'):
                    continue
    
                itempath = os.path.join(path, item)
    
                if os.path.isdir(itempath):
                    self._print_dir(itempath, indent + 2, depth + 1)
                else:
                    if self.show_files:
                        print(' ' * indent + '📄 ' + item)
    
    
    
    
    
    # 创建类的实例
    tree = DirectoryTree(os.getcwd())
    
    # 使用默认方法打印
    print("Default:")
    tree.print_tree()
    
    # 使用带计数的方法打印
    print("\nWith Count:")
    tree.print_tree(method='with_count')
    
    # 使用只打印文件的方法
    print("\nFiles Only:")
    tree.print_tree(method='files_only')
    
    # 使用emoji
    print("\nWith Symbols:")
    tree.print_tree(method='with_symbols')
    
    print('================================================================')
    
    enhancedtree = EnhancedDirectoryTree(os.getcwd())
    
    # Default print
    enhancedtree.print_tree()
    
    print("\n---\n")
    
    # Configure settings to show hidden files, but only up to depth 2 and only directories
    enhancedtree.display_settings(show_hidden=True, depth_limit=2, show_files=False)
    enhancedtree.print_tree()
    
    print("\n---\n")
    
    # Configure settings to show only files up to depth 1
    enhancedtree.display_settings(show_files=True, show_dirs=False, depth_limit=1)
    enhancedtree.print_tree()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • os.getcwd(): 返回当前工作目录的路径名

    • os.path.basename(path): 返回路径名 path 的基本名称,即去掉路径中的目录部分,只保留文件或目录的名称部分。

    • os.listdir(path): 返回指定路径 path 下的所有文件和目录的名称列表。

    • os.path.isdir(path): 判断路径 path 是否为一个目录,如果是则返回 True,否则返回 False

    • os.path.join(path, *paths): 将多个路径组合成一个完整的路径名。这个函数会自动根据操作系统的不同使用不同的路径分隔符。

    • 上面两个类里面的函数其实就是用到递归,第二个类的那个函数可以设置递归深度

  • 相关阅读:
    WebGoat搭建和Yakit学习
    nginx平滑升级解决 nginx 安全漏洞(CVE-2021-23017)和NGINX 环境问题漏洞(CVE-2019-20372)
    EasyExcel 读取数据为null
    SQL 基本命令
    Android Studio javadoc 编译的时候一直报错 java.lang.IllegalArgumentException
    【Transformers】第 10 章:服务 Transformer 模型
    2023转行要趁早!盘点网络安全的岗位汇总
    推挽输出和开漏输出-三极管-mos管
    二叉树,关于数字计算的高频考点
    基于 SPI 的增强式插件框架设计
  • 原文地址:https://blog.csdn.net/qq_52431436/article/details/133850490