tree.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import os
  2. def print_tree(root_path, ignore_dirs=None, prefix=""):
  3. """
  4. 打印目录树(美观版)
  5. :param root_path: 目录绝对路径
  6. :param ignore_dirs: 要忽略的目录列表
  7. :param prefix: 树状前缀(递归用)
  8. """
  9. if ignore_dirs is None:
  10. ignore_dirs = []
  11. try:
  12. entries = [e for e in os.listdir(root_path) if e not in ignore_dirs]
  13. except PermissionError:
  14. print(prefix + "└─ [Permission Denied]")
  15. return
  16. entries.sort()
  17. total = len(entries)
  18. for idx, entry in enumerate(entries):
  19. path = os.path.join(root_path, entry)
  20. is_last = (idx == total - 1)
  21. connector = "└─ " if is_last else "├─ "
  22. print(prefix + connector + entry)
  23. if os.path.isdir(path):
  24. extension = " " if is_last else "│ "
  25. print_tree(path, ignore_dirs, prefix + extension)
  26. if __name__ == "__main__":
  27. root_dir = input("请输入目录绝对路径: ").strip()
  28. ignore = input("请输入要忽略的目录,用逗号分隔(可留空): ").strip()
  29. ignore_list = [d.strip() for d in ignore.split(",") if d.strip()]
  30. # 打印根目录
  31. print(os.path.basename(root_dir))
  32. print_tree(root_dir, ignore_list)