python树状打印项目路径的实现

 更新时间:2023年10月16日 08:33:50   作者:临风而眠  
在Python中,要打印当前路径,可以使用os模块中的getcwd()函数,本文主要介绍了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()

  • os.getcwd(): 返回当前工作目录的路径名。

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

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

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

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

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

到此这篇关于python树状打印项目路径的实现的文章就介绍到这了,更多相关python树状打印路径内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

相关文章

  • python 连接各类主流数据库的实例代码

    python 连接各类主流数据库的实例代码

    下面小编就为大家分享一篇python 连接各类主流数据库的实例代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-01-01
  • Python如何获取pid和进程名字

    Python如何获取pid和进程名字

    这篇文章主要介绍了Python如何获取pid和进程名字的方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-09-09
  • python pyppeteer 破解京东滑块功能的代码

    python pyppeteer 破解京东滑块功能的代码

    这篇文章主要介绍了python pyppeteer 破解京东滑块功能的代码,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-03-03
  • Pytorch释放显存占用方式

    Pytorch释放显存占用方式

    今天小编就为大家分享一篇Pytorch释放显存占用方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-01-01
  • Python使用docx模块编辑Word文档

    Python使用docx模块编辑Word文档

    docx提供了一组功能丰富的函数和方法,用于创建、修改和读取Word文档,Python可以用它对word文档进行大批量的编辑,下面小编就来通过一些示例为大家好好讲讲吧
    2023-07-07
  • Windows下快速配置Python+OpenCV环境指南

    Windows下快速配置Python+OpenCV环境指南

    本文介绍了如何在Windows下使用uv工具快速配置Python环境并安装OpenCV,步骤包括安装Python、uv工具、创建虚拟环境、安装OpenCV及其扩展,并验证安装,感兴趣的朋友跟随小编一起看看吧
    2026-01-01
  • opencv 形态学变换(开运算,闭运算,梯度运算)

    opencv 形态学变换(开运算,闭运算,梯度运算)

    这篇文章主要介绍了opencv 形态学变换(开运算,闭运算,梯度运算),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-07-07
  • 使用Python代码识别股票价格图表模式实现

    使用Python代码识别股票价格图表模式实现

    这篇文章主要为大家介绍了使用Python代码识别股票价格图表模式的实现示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • Python迭代器的应用场景分析

    Python迭代器的应用场景分析

    这篇文章给大家介绍Python迭代器的应用场景分析,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2026-02-02
  • 基于python代码批量处理图片resize

    基于python代码批量处理图片resize

    这篇文章主要介绍了基于python代码批量处理图片resize,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-06-06

最新评论