Finding the common path in a list of paths in python:
Python os.path module provides a lot of different methods to work with paths. This module is under os module. So, we can use it directly by importing os and we don’t have to integrate any other third party libs.
This module provides one method called commonpath or os.path.commonpath() that can be used to get the longest common subpath from a list of paths.
In this post, we will learn how to use os.path.commonpath method with examples.
Definition of os.path.commonpath:
os.path.commonpath is defined as below:
os.path.commonpath(path_list)
path_list is the list of paths. It returns the longest common subpath of each paths.
It raises ValueError if the list contains both absolute and relative paths, or if paths are empty, or if the paths are in different drives.
This method returns a valid path.
Starting from python 3.6, it can take a sequence of path like objects.
Example of os.path.commonpath:
Let’s take a look at the example below:
import os
given_paths = ['/Users/cvc/Downloads/file.mp4', '/Users/cvc/Downloads/', '/Users/cvc/Documents/', '/Users/cvc/Desktop/']
print(os.path.commonpath(given_paths))
If you run this program, it will print the below output:
/Users/cvc
If you look at the paths, /Users/cvc is the common path among all.
ValueError:
This method throws a ValueError if the paths are empty, or if the paths are in different drives, of if the list contains both absolute and relative paths.
For the below example:
import os
given_paths = ['', '/Users/cvc/Desktop/']
print(os.path.commonpath(given_paths))
It will throw one ValueError.
raise ValueError("Can't mix absolute and relative paths")
You might also like:
- Python dictionary get() method explanation with example
- Python program to check if a path exists
- Python os.path.lexists() method explanation with example
- How to check if a path is file or directory in Python
- How to get the last access time of a path in python
- Python program to get the last modified time of a path