Simplify a File Path in Python with a Stack

Uses a stack to normalize an absolute Unix path by handling '.', '..', and duplicate slashes.

Easy Python 3.8+ Aug 9, 2026 Algorithms & data structures 11 views 0 copies

Python code

28 lines
Python 3.8+
from pathlib import PurePosixPath

def simplify_path(path: str) -> str:
    tokens = path.split('/')
    stack = []
    
    for token in tokens:
        if not token or token == '.':
            continue
        if token == '..':
            if stack:
                stack.pop()
        else:
            stack.append(token)
    
    return '/' + '/'.join(stack)


if __name__ == "__main__":
    paths = [
        "/home/",
        "/a/./b/../../c/",
        "/../",
        "/home//foo/",
        "/a/b/c/../../../"
    ]
    for p in paths:
        print(f"simplify_path('{p}') = '{simplify_path(p)}'")

Output

stdout
simplify_path('/home/') = '/home'
simplify_path('/a/./b/../../c/') = '/c'
simplify_path('/../') = '/'
simplify_path('/home//foo/') = '/home/foo'
simplify_path('/a/b/c/../../../') = '/'

How it works

The path is split on '/' so each component becomes a token. Empty tokens (from duplicate slashes) and '.' are ignored because they don't change the directory. When a '..' appears, we pop the last directory from the stack to go up one level, but only if the stack isn't empty to avoid going above root. After processing, the stack contains the valid directory components, and joining them with '/' and prepending '/' reconstructs the simplified path.

Common mistakes

  • Popping from an empty stack when '..' appears at root
  • Forgetting to handle empty tokens from duplicate slashes
  • Hardcoding os.path functions instead of implementing the algorithm
  • Not considering that '.' and '..' can appear mid-string

Variations

  1. Use os.path.normpath for a built-in solution
  2. Use a list as the stack and join at the end instead of a deque

Real-world use cases

  • Normalizing URLs in a web scraper or crawler before storing or fetching links.
  • Cleaning user input file paths in a CLI tool before accessing filesystem resources.
  • Resolving relative paths in a build system to determine absolute targets.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.