Program for longest common directory path in Python

In this tutorial, we are going to write a program that finds the longest common path from the given list of paths. Let's see an example to understand the problem statement more clearly.


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

We can solve the problem using os module very easily. Let's see the steps to solve the

  • Import the os module.
  • Initialize the list of paths to find the longest common path.
  • Find the common prefix of all paths using os.path.commonprefix(paths) and store it in variable.
  • And extract the directory from the common prefix using os.path.dirname(common_prefix).


 Live Demo

# importing the os module
import os
# initializing the paths
paths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorials
point/javascript', 'home/tutorialspoint/react', 'home/tutorialspoint/django']
# finding the common prefix
common_prefix = os.path.commonprefix(paths)
# extracting the directory from the common prefix
longest_common_directory = os.path.dirname(common_prefix)
# printing the long common path


If you run the above code, then you will get the following result.



If you have any queries regarding the tutorial, mention them in the comment section.