AppDividend
Latest Code Tutorials

Python os.path.commonpath() Function: Complete Guide

0

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.

Python os.path.commonpath()

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.

Syntax

os.path.commonpath(list)

Arguments

It is a list of path-like objects. A path-like object is either a string or bytes object representing a path.

Return Value

The commonpath() method returns a string value representing the longest common sub-path in the input list.

Example

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)

Output

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)

Output

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.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.