Program for longest common directory path in Python

In this tutorial, we are going to write a program that finds the longest common directory path from a given list of paths. This is useful when working with file systems or organizing directory structures.

Problem Statement

Given a list of file paths, we need to find the longest directory path that is common to all of them ?

paths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorialspoint/javascript',
         'home/tutorialspoint/react', 'home/tutorialspoint/django']

Expected Output: home/tutorialspoint

Using os.path.commonprefix()

Python's os module provides os.path.commonprefix() to find the common prefix of multiple paths. We then extract the directory using os.path.dirname().

Steps

  • Import the os module
  • Initialize the list of paths
  • Find the common prefix using os.path.commonprefix(paths)
  • Extract the directory from the common prefix using os.path.dirname()

Example

# importing the os module
import os

# initializing the paths
paths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorialspoint/javascript', 
         'home/tutorialspoint/react', 'home/tutorialspoint/django']

# finding the common prefix
common_prefix = os.path.commonprefix(paths)
print("Common prefix:", common_prefix)

# extracting the directory from the common prefix
longest_common_directory = os.path.dirname(common_prefix)

# printing the longest common directory path
print("Longest common directory:", longest_common_directory)
Common prefix: home/tutorialspoint/
Longest common directory: home/tutorialspoint

Alternative Approach: Manual Implementation

We can also implement this manually by splitting paths and comparing components ?

def find_longest_common_path(paths):
    if not paths:
        return ""
    
    # Split all paths into components
    split_paths = [path.split('/') for path in paths]
    
    # Find minimum length to avoid index errors
    min_length = min(len(path) for path in split_paths)
    
    common_parts = []
    for i in range(min_length):
        # Check if all paths have the same component at position i
        if all(split_paths[0][i] == path[i] for path in split_paths):
            common_parts.append(split_paths[0][i])
        else:
            break
    
    return '/'.join(common_parts)

# Test the function
paths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorialspoint/javascript']
result = find_longest_common_path(paths)
print("Longest common directory:", result)
Longest common directory: home/tutorialspoint

Comparison

Method Pros Cons
os.path.commonprefix() Built-in, concise Works on string level, not path-aware
Manual implementation Path-aware, more control More code, need to handle edge cases

Conclusion

Use os.path.commonprefix() combined with os.path.dirname() for a simple solution. For more control over path handling, implement a manual approach that splits and compares path components.

Updated on: 2026-03-25T08:57:40+05:30

521 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements