The os
module in the standard library includes the path sub-module which contains useful functions for working with and manipulating paths.
Among the various functions defined in the path
sub-module, we have commonprefix()
and the commonpath()
functions. The two function serves almost a similar purpose. Actually the, commonpath()
function is merely a specialized version of the commonprefix(
) function.
The commonprefix()
function takes in a list of strings and returns the common prefix string out of them while the commonpath()
function takes a list of paths and returns the common sub-path.
The commonpath()
function thus works on actual paths, whereas the commonprefix()
function works on mere strings that may or may not contain valid path components.
To use either of these functions we will first need to import them in our program as follows.
from os.path import commonprefix, commonpath
The commonprefix() function
The commonprefix()
is used with strings that may or may not represent valid paths to get the longest leading component.
commonprefix(m)
m | An iterable such as a list containing the pathnames. |
In the above example, we have a list of paths in which all the path have a common prefix that is "C:\users\john\desktop\". You should note that the function works on mare strings, it does not need to have the structure of a path, the following example demonstrates this better.
The commonpath() function
While the commonprefix()
function works on mere strings, the commonpath()
function expects strings that are structured as paths.
commonpath(paths)
paths |
An iterable containing paths. |
#import the function
from os.path import commonpath
paths = [r"C:\users\john\desktop\project",
r"C:\users\john\desktop\images",
r"C:\users\john\desktop\book.pdf",
r"C:\users\john\desktop\project",
]
basepath = commonpath(paths)
print(basepath)
C:\users\john\desktop
If the strings in the iterables are not structured as paths, the function may return undependable results.