How to list directory tree structure in python?

The given task is to list the directory tree structure, i.e., we need to print the hierarchy of folders and files starting from a specified root directory. This is similar to how the tree command works in Linux or Windows by showing nested folders and files in a structured and indented format.

In this article, we will see different methods in Python to list the directory tree structure using os.walk(), pathlib, and os.listdir().

Using os.walk() Method

The os.walk() method in Python is used to generate the file names and folder names in a directory tree by parsing through the tree in either a top-down or bottom-up approach.

Example

Following is the example, which shows how to use the os.walk() method to list the directory tree structure −

import os
import tempfile

# Create a sample directory structure for demonstration
def create_sample_structure():
    base_dir = tempfile.mkdtemp(prefix="sample_")
    
    # Create directories
    os.makedirs(os.path.join(base_dir, "folder1"))
    os.makedirs(os.path.join(base_dir, "folder2"))
    os.makedirs(os.path.join(base_dir, "folder1", "subfolder"))
    
    # Create files
    open(os.path.join(base_dir, "folder1", "sample1.txt"), 'w').close()
    open(os.path.join(base_dir, "folder1", "sample2.txt"), 'w').close()
    open(os.path.join(base_dir, "folder2", "sample.txt"), 'w').close()
    open(os.path.join(base_dir, "folder1", "subfolder", "nested.txt"), 'w').close()
    
    return base_dir

def list_dir_tree(start_path):
    for root, dirs, files in os.walk(start_path):
        # Determine indentation level
        level = root.replace(start_path, '').count(os.sep)
        indent = ' ' * 4 * level
        # Print folder name
        print(f'{indent}{os.path.basename(root)}/')
        sub_indent = ' ' * 4 * (level + 1)
        # Print files in the folder
        for f in files:
            print(f'{sub_indent}{f}')

# Create sample structure and list it
sample_path = create_sample_structure()
print("Directory tree structure:")
list_dir_tree(sample_path)
Directory tree structure:
/
    folder1/
        sample1.txt
        sample2.txt
        subfolder/
            nested.txt
    folder2/
        sample.txt

Using pathlib.Path.iterdir() Method

The pathlib.Path.iterdir() method provides an object-oriented approach to iterate over directory contents. It returns an iterator of all files and subdirectories and can be used recursively to build a directory tree structure.

Example

Below is an example that shows how to use pathlib.Path.iterdir() method to list the directory tree structure −

from pathlib import Path
import tempfile
import os

# Create a sample directory structure
def create_sample_structure():
    base_dir = Path(tempfile.mkdtemp(prefix="sample_"))
    
    # Create directories and files
    (base_dir / "folder1").mkdir()
    (base_dir / "folder2").mkdir()
    (base_dir / "folder1" / "subfolder").mkdir()
    
    (base_dir / "folder1" / "sample1.txt").touch()
    (base_dir / "folder1" / "sample2.txt").touch()
    (base_dir / "folder2" / "sample.txt").touch()
    (base_dir / "folder1" / "subfolder" / "nested.txt").touch()
    
    return base_dir

def list_tree(path, level=0):
    for item in sorted(path.iterdir()):
        print('    ' * level + item.name + ('/' if item.is_dir() else ''))
        if item.is_dir():
            list_tree(item, level + 1)

# Create sample structure and list it
sample_path = create_sample_structure()
print("Directory tree structure:")
list_tree(sample_path)
Directory tree structure:
folder1/
    sample1.txt
    sample2.txt
    subfolder/
        nested.txt
folder2/
    sample.txt

Using os.listdir() with Recursion

The os.listdir() method can also be used with recursion to create a directory tree display. This approach gives more control over the formatting.

Example

import os
import tempfile

def create_sample_structure():
    base_dir = tempfile.mkdtemp(prefix="sample_")
    
    os.makedirs(os.path.join(base_dir, "docs"))
    os.makedirs(os.path.join(base_dir, "src", "utils"))
    
    open(os.path.join(base_dir, "README.md"), 'w').close()
    open(os.path.join(base_dir, "docs", "guide.txt"), 'w').close()
    open(os.path.join(base_dir, "src", "main.py"), 'w').close()
    open(os.path.join(base_dir, "src", "utils", "helper.py"), 'w').close()
    
    return base_dir

def list_directory_tree(directory, prefix=""):
    try:
        items = sorted(os.listdir(directory))
        for i, item in enumerate(items):
            path = os.path.join(directory, item)
            is_last = i == len(items) - 1
            
            # Choose the appropriate prefix symbols
            current_prefix = "??? " if is_last else "??? "
            print(prefix + current_prefix + item)
            
            # If it's a directory, recurse into it
            if os.path.isdir(path):
                extension = "    " if is_last else "?   "
                list_directory_tree(path, prefix + extension)
                
    except PermissionError:
        print(prefix + "??? [Permission Denied]")

# Create sample structure and display tree
sample_path = create_sample_structure()
print("Directory tree structure:")
print(os.path.basename(sample_path))
list_directory_tree(sample_path)
Directory tree structure:
sample_tmpxyz123
??? README.md
??? docs
?   ??? guide.txt
??? src
    ??? main.py
    ??? utils
        ??? helper.py

Comparison

Method Approach Best For
os.walk() Iterator-based traversal Simple tree listing with minimal code
pathlib.iterdir() Object-oriented, recursive Modern Python code, better path handling
os.listdir() Manual recursion Custom formatting and tree symbols

Conclusion

Use os.walk() for simple directory traversal, pathlib for modern object-oriented approach, or os.listdir() with recursion for custom tree formatting. Each method offers different levels of control and formatting options for displaying directory structures.

Updated on: 2026-03-24T18:28:45+05:30

9K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements