Python os.path.commonpath() Function: Complete Guide
The os module in Python provides a lot of different methods and functions to work with system paths. The os.path.commonpath() function returns the common path instead of the common string prefix.
The os.path.commonpath() is a built-in Python method used to find the longest common sub-path in a list of paths. The commonpath() method can raise a ValueError if the specified list of paths either contains both absolute and relative path or is empty.
It is a list of path-like objects. A path-like object is either a string or bytes object representing a path.
The commonpath() method returns a string value representing the longest common sub-path in the input list.
Let’s define a list of three paths and find the longest common path using the os.path.commonpath() function.
import os paths = ['/Users/krunal/Desktop', '/Users/krunal/Desktop/code', '/Users/krunal/Desktop/datasets'] prefix = os.path.commonpath(paths) print("The Longest Common Path Is: ", prefix)
The Longest Common Path Is: /Users/krunal/Desktop
You can see that the “/Users/krunal/Desktop” string is common in all three paths. So it returns that common long string.
Mix absolute and relative path
If you mix the absolute path and relative path in the list and apply the commonpath() function on them, then it raises the ValueError.
import os paths = ['Users/krunal', '/Users/krunal/Desktop/code', 'Users/krunal/Desktop'] prefix = os.path.commonpath(paths) print("The Longest Common Path Is: ", prefix)
Traceback (most recent call last): File "/Users/krunal/Desktop/code/pyt/database/app.py", line 7, in <module> prefix = os.path.commonpath(paths) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/posixpath.py", line 510, in commonpath raise ValueError("Can't mix absolute and relative paths") from None ValueError: Can't mix absolute and relative paths
In this example, we mixed the absolute path with the relative path in the list and then passed that list to the commonpath() function.
That’s it for the os.path.commonpath() function in Python.