Logo
AI Engineer at

Directory Tree Printer

May 4th, 2025 - Tags: Markdown and Python

Directory Tree Printer

This script is designed to print the directory tree of a specified directory. It recursively lists all the subdirectories and files, excluding hidden entries (those starting with a dot .). The output is formatted to clearly visualize the directory structure.

Features

How It Works

  1. List Directory Entries: The script first lists all entries in the specified directory.
  2. Separate Directories and Files: It separates directories and files, and sorts them.
  3. Combine Sorted Entries: Directories are listed first, followed by files.
  4. Print Entries: Each entry is printed with the appropriate connector and indentation.
  5. Recurse for Subdirectories: If an entry is a directory, the script recurses into it with updated indentation and prefix.

Example Usage

import os

def print_directory_tree(directory, indent="", prefix=""):
    # Get list of all entries in the directory
    entries = os.listdir(directory)
    # Separate directories and files, excluding hidden entries
    dirs = sorted([e for e in entries if os.path.isdir(os.path.join(directory, e)) and not \
                   e.startswith('.')])
    files = sorted([e for e in entries if not os.path.isdir(os.path.join(directory, e)) and not\
                    e.startswith('.')])
    # Combine: directories first, then files
    sorted_entries = dirs + files
    
    for index, entry in enumerate(sorted_entries):
        path = os.path.join(directory, entry)
        # Determine connector based on whether it's the last entry
        connector = "└──" if index == len(sorted_entries) - 1 else "├──"
        # Print current entry
        print(f"{indent}{prefix}{connector} {entry}")
        # If it's a directory, recurse with updated indent and prefix
        if os.path.isdir(path):
            # Use different prefix for last entry to align properly
            new_prefix = "    " if index == len(sorted_entries) - 1 else "│   "
            print_directory_tree(path, indent + new_prefix, "")
            
# Example usage
directory = "./sample_data"  # Specify directory
print(os.path.basename(os.path.abspath(directory)))  # Print root directory name
print_directory_tree(directory)

Example Output

sample_data
├── dir1
│   ├── file1.txt
│   └── file2.txt
├── dir2
│   └── file3.txt
└── file4.txt

This output shows a sample directory structure with two subdirectories (dir1 and dir2) and three files (file1.txt, file2.txt, and file4.txt).

Notes

The script excludes hidden directories and files by default. The connectors and indentation are designed to create a clear and visually appealing directory tree. Feel free to modify the script to suit your specific needs!

This markdown code provides a comprehensive introduction to the directory tree printing script, including its features, how it works, example usage, and expected output.