当前位置: 首页 > news >正文

python树状打印项目路径

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

import osclass DirectoryTree:def __init__(self, path):self.path = pathdef 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) - dirsprint(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 = pathself.show_hidden = Falseself.depth_limit = Noneself.show_files = Trueself.show_dirs = Truedef display_settings(self, show_hidden=False, depth_limit=None, show_files=True, show_dirs=True):self.show_hidden = show_hiddenself.depth_limit = depth_limitself.show_files = show_filesself.show_dirs = show_dirsdef 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:returnif self.show_dirs:print(' ' * indent + '📁 ' + os.path.basename(path))for item in sorted(os.listdir(path)):# Check for hidden files/foldersif not self.show_hidden and item.startswith('.'):continueitempath = 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): 将多个路径组合成一个完整的路径名。这个函数会自动根据操作系统的不同使用不同的路径分隔符。

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

http://www.lryc.cn/news/194150.html

相关文章:

  • mysql误删误操作恢复数据,比传统方式和binlog2sql更快速用的恢复方式-reverse_sql恢复数据(单表多表)
  • CORE: Cooperative Reconstruction for Multi-Agent Perception 论文阅读
  • MySQL连接方式: Unix套接字 TCP/IP
  • TSINGSEE青犀智慧城市数字基座解决方案,助力城市数字化转型
  • 【JavaEE】初识网络
  • UGUI交互组件ScrollBar
  • DamiBus v0.51 发布
  • [OpenJDK:环境变量配置]:填充Profile并修改默认配置
  • 连接mysql报错 :Host ‘xxx.xx.x.x‘ is not allowed to connect to this MySQL server
  • Qt 布局(QSplitter 类QDockWidget 类) 总结
  • git-ssh-key协议同步文件
  • 2018-2019 ACM-ICPC, Asia Nanjing Regional Contest G. Pyramid(组合数学 计数)
  • C++学习——string 详解(即C++字符串详解)
  • LeetCode 1 两数之和
  • 【opencv】windows10下opencv4.8.0-cuda Python版本源码编译教程
  • 【1day】用友U8Cloud未授权访问漏洞学习
  • 基于单片机智能汽车仪表设计系统
  • java double 保留两位小数
  • 计网第六章(应用层)(三)(文件传输协议FTP)
  • 微信小程序canvas画布绘制base64图片并保存图片到相册中
  • Hadoop3教程(八):MapReduce中的序列化概述
  • Flash-Attention
  • 发布npm包质量分测试
  • 基于适应度相关优化的BP神经网络(分类应用) - 附代码
  • 复杂网络 | 利用复杂网络预测城市空间流量
  • 【1】c++11新特性(稳定性和兼容性)—>原始字面量
  • 学习pytorch13 神经网络-搭建小实战Sequential的使用
  • TCP发送接口(如send(),write()等)的返回值与成功发送到接收端的数据量无直接关系
  • 【Python、Qt】使用QItemDelegate实现单元格的富文本显示+复选框功能
  • 【JVM】JVM类加载机制