Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
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.
Input
paths = ['home/tutorialspoint/python', 'home/tutorialspoint/c', 'home/tutorialspoint/javascript', 'home/tutorialspoint/react', 'home/tutorialspoint/django']
/home/tutorialspoint/
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).
Example
# 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 print(longest_common_directory)
Output
If you run the above code, then you will get the following result.
home/tutorialspoint
Conclusion
If you have any queries regarding the tutorial, mention them in the comment section.
Advertisements
