🔍 Code Extractor

function show_directory_tree

Maturity: 54

Recursively displays a visual tree structure of a directory and its contents, showing files with sizes and subdirectories up to a specified depth.

File:
/tf/active/vicechatdev/e-ink-llm/cloudtest/test_complete_suite.py
Lines:
136 - 168
Complexity:
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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function print_node_tree 72.2% similar

    Recursively prints a hierarchical tree visualization of nodes with icons, names, file counts, and modification dates to the console.

    From: /tf/active/vicechatdev/e-ink-llm/cloudtest/analyze_replica.py
  • function build_document_tree_recursive 68.2% similar

    Recursively builds a complete hierarchical tree structure of documents and folders from a target directory path, filtering for supported file types and skipping hidden/cache directories.

    From: /tf/active/vicechatdev/docchat/app.py
  • function test_folder_structure 58.7% similar

    Tests SharePoint folder structure by listing root-level folders, displaying their contents, and providing a summary of total folders and documents.

    From: /tf/active/vicechatdev/SPFCsync/test_folder_structure.py
  • function parse_directory_listing_debug 57.7% similar

    A debug version of a directory listing parser that extracts and categorizes file entries with detailed console output for troubleshooting.

    From: /tf/active/vicechatdev/e-ink-llm/cloudtest/debug_rm_parsing.py
  • function build_document_tree_lazy 56.5% similar

    Builds a single-level document tree structure for lazy loading, scanning only immediate children of a target directory without recursively loading subdirectories.

    From: /tf/active/vicechatdev/docchat/app.py
← Back to Browse