Generate a Beautiful Folder Tree Visualization in Python
A Python utility that creates a visual tree of a directory structure, excluding common files, with configurable depth.
Python code
36 linesimport os
from pathlib import Path
class FolderTree:
def __init__(self, root_path=".", ignore_list=None, max_depth=3):
self.root = Path(root_path)
self.ignore = set(ignore_list or [".git", "__pycache__", ".DS_Store"])
self.max_depth = max_depth
def generate(self):
tree_lines = [f"{self.root.name}/"]
self._add_children(self.root, "", 0, tree_lines)
return "\n".join(tree_lines)
def _add_children(self, path, prefix, depth, tree_lines):
if depth >= self.max_depth:
return
try:
items = sorted(path.iterdir(), key=lambda x: (x.is_file(), x.name))
items = [item for item in items if item.name not in self.ignore]
for i, item in enumerate(items):
is_last = i == len(items) - 1
connector = "└── " if is_last else "├── "
tree_lines.append(f"{prefix}{connector}{item.name}")
if item.is_dir() and depth < self.max_depth - 1:
extension = " " if is_last else "│ "
self._add_children(item, prefix + extension, depth + 1, tree_lines)
except PermissionError:
tree_lines.append(f"{prefix}└── [Permission Denied]")
if __name__ == "__main__":
import sys
path = sys.argv[1] if len(sys.argv) > 1 else "."
depth = int(sys.argv[2]) if len(sys.argv) > 2 else 3
tree = FolderTree(path, max_depth=depth)
print(tree.generate())
Output
myproject/
├── README.md
├── src/
│ ├── __init__.py
│ ├── main.py
│ └── utils.py
└── tests/
├── __init__.py
└── test_main.py
How it works
The FolderTree class uses Path.iterdir() with sorting so directories appear before files, creating a clear visual hierarchy. The private _add_children method builds the tree recursively, adding tree-drawing characters (like "├──" and "└──") and indentation prefixes to mimic standard Unix tree output. Ignored folders (common cache and version control directories) are skipped to keep the display clean. Permission errors are gracefully caught and shown as a placeholder instead of crashing.
Common mistakes
- Forgetting to handle `PermissionError` on restricted directories, which would crash the script.
- Using the same prefix for all items regardless of nesting level, breaking the tree layout.
- Not sorting items, so the tree appears in arbitrary filesystem order.
- Setting `max_depth` too low, resulting in an empty or incomplete tree.
Variations
- Use `os.walk` with manual indentation for an alternate implementation.
- Include file sizes by calling `os.path.getsize` inside the recursion.
Real-world use cases
- Documenting project structure in README or onboarding guides without manual typing.
- Generating folder snapshots for audit logs or deployment checklists.
- Building a quick CLI overview of a complex nested data directory during debugging.
Sponsored
More from Files & data
- Audit File Permissions Across a Project in Python easy
- Automatically Detect Corrupted Files Using SHA-256 Checksums in Python easy
- Automatically Highlight Data Validation Errors Inside Excel Files in Python easy
- Build a Command-Line To-Do List Application with Data Persistence in Python easy
- Build a Personal Work Hours Tracker in Python medium
- Build a Python Script That Detects and Deletes Empty Files Across Folders easy
Keep learning
Related tutorials and quizzes for this topic.