dir_tree.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import os
  2. # 需要排除的目录 & 文件(你可以自定义)
  3. EXCLUDED_DIRS = {
  4. ".git",
  5. ".idea",
  6. ".venv",
  7. "build",
  8. "dist",
  9. "__pycache__",
  10. "desktop",
  11. "logs",
  12. "models",
  13. "documents",
  14. }
  15. EXCLUDED_FILES = {".DS_Store", "Thumbs.db"}
  16. def print_directory_tree(start_path=".", indent=""):
  17. try:
  18. files = sorted(os.listdir(start_path))
  19. except PermissionError:
  20. return
  21. files = [f for f in files if f not in EXCLUDED_FILES] # 过滤不需要的文件
  22. dirs = [
  23. d
  24. for d in files
  25. if os.path.isdir(os.path.join(start_path, d)) and d not in EXCLUDED_DIRS
  26. ]
  27. files = [f for f in files if os.path.isfile(os.path.join(start_path, f))]
  28. for index, file in enumerate(dirs + files):
  29. path = os.path.join(start_path, file)
  30. is_last = index == len(dirs + files) - 1
  31. prefix = "└── " if is_last else "├── "
  32. print(indent + prefix + file)
  33. if os.path.isdir(path):
  34. next_indent = indent + (" " if is_last else "│ ")
  35. print_directory_tree(path, next_indent)
  36. if __name__ == "__main__":
  37. print_directory_tree("..")