function show_directory_tree
Recursively displays a visual tree structure of a directory and its contents, showing files with sizes and subdirectories up to a specified depth.
/tf/active/vicechatdev/e-ink-llm/cloudtest/test_complete_suite.py
136 - 168
moderate
Purpose
This function provides a formatted, hierarchical visualization of a filesystem directory structure. It's useful for exploring directory contents, debugging file organization, or providing users with a visual overview of folder structures. The function includes features like depth limiting, item count limiting (20 per directory), file size display for larger files (>0.1MB), and graceful error handling for permission issues.
Source Code
def show_directory_tree(path: Path, max_depth: int = 3, current_depth: int = 0, prefix: str = ""):
"""Show directory tree structure"""
if current_depth > max_depth:
return
try:
items = sorted(path.iterdir(), key=lambda x: (x.is_file(), x.name.lower()))
for i, item in enumerate(items[:20]): # Limit to first 20 items per directory
is_last = i == len(items) - 1
current_prefix = "└── " if is_last else "├── "
if item.is_file():
size_mb = item.stat().st_size / (1024 * 1024)
if size_mb > 0.1:
print(f"{prefix}{current_prefix}📄 {item.name} ({size_mb:.1f}MB)")
else:
print(f"{prefix}{current_prefix}📄 {item.name}")
else:
print(f"{prefix}{current_prefix}📁 {item.name}/")
# Recurse into directories
if current_depth < max_depth:
next_prefix = prefix + (" " if is_last else "│ ")
show_directory_tree(item, max_depth, current_depth + 1, next_prefix)
if len(items) > 20:
print(f"{prefix} ... ({len(items) - 20} more items)")
except PermissionError:
print(f"{prefix} [Permission Denied]")
except Exception as e:
print(f"{prefix} [Error: {e}]")
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
path |
Path | - | positional_or_keyword |
max_depth |
int | 3 | positional_or_keyword |
current_depth |
int | 0 | positional_or_keyword |
prefix |
str | '' | positional_or_keyword |
Parameter Details
path: A Path object representing the directory to display. Must be a valid pathlib.Path instance pointing to an existing directory.
max_depth: Maximum depth of subdirectories to traverse. Default is 3. Controls how many levels deep the tree will display. A value of 0 shows only the immediate directory contents.
current_depth: Internal parameter tracking the current recursion depth. Should typically be left at default (0) when calling the function. Used internally during recursive calls.
prefix: Internal parameter for formatting the tree structure with proper indentation and branch characters. Should typically be left at default (empty string) when calling the function. Used internally during recursive calls to maintain visual alignment.
Return Value
This function returns None. It produces output by printing directly to stdout, displaying the directory tree structure with Unicode box-drawing characters (├──, └──, │) and emoji icons (📄 for files, 📁 for directories).
Dependencies
pathlib
Required Imports
from pathlib import Path
Usage Example
from pathlib import Path
def show_directory_tree(path: Path, max_depth: int = 3, current_depth: int = 0, prefix: str = ""):
"""Show directory tree structure"""
if current_depth > max_depth:
return
try:
items = sorted(path.iterdir(), key=lambda x: (x.is_file(), x.name.lower()))
for i, item in enumerate(items[:20]):
is_last = i == len(items) - 1
current_prefix = "└── " if is_last else "├── "
if item.is_file():
size_mb = item.stat().st_size / (1024 * 1024)
if size_mb > 0.1:
print(f"{prefix}{current_prefix}📄 {item.name} ({size_mb:.1f}MB)")
else:
print(f"{prefix}{current_prefix}📄 {item.name}")
else:
print(f"{prefix}{current_prefix}📁 {item.name}/")
if current_depth < max_depth:
next_prefix = prefix + (" " if is_last else "│ ")
show_directory_tree(item, max_depth, current_depth + 1, next_prefix)
if len(items) > 20:
print(f"{prefix} ... ({len(items) - 20} more items)")
except PermissionError:
print(f"{prefix} [Permission Denied]")
except Exception as e:
print(f"{prefix} [Error: {e}]")
# Example usage:
my_directory = Path('/home/user/documents')
show_directory_tree(my_directory, max_depth=2)
# Or with current directory:
show_directory_tree(Path.cwd())
Best Practices
- Use appropriate max_depth values to avoid excessive recursion in deep directory structures
- Be cautious when running on system directories or large filesystems as it may take time to traverse
- The function limits output to 20 items per directory to prevent overwhelming output
- Handle the case where the initial path might not exist or be accessible before calling
- Consider redirecting output to a file for large directory structures: show_directory_tree(path) > output.txt
- The current_depth and prefix parameters are for internal use and should not be modified by external callers
- File sizes are only displayed for files larger than 0.1MB to reduce clutter
- The function gracefully handles PermissionError and other exceptions, continuing execution rather than crashing
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function print_node_tree 72.2% similar
-
function build_document_tree_recursive 68.2% similar
-
function test_folder_structure 58.7% similar
-
function parse_directory_listing_debug 57.7% similar
-
function build_document_tree_lazy 56.5% similar