Simplify a File Path in Python with a Stack
Uses a stack to normalize an absolute Unix path by handling '.', '..', and duplicate slashes.
Python code
28 linesfrom 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
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
- Use os.path.normpath for a built-in solution
- 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
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.