AppDividend
Latest Code Tutorials

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

0

The OS module provides functions that allow you to interact with the underlying operating system that Python is running on Windows, Mac, or Linux. The os module implements a compact way of using operating system dependent functionality.

Python os.path.commonprefix()

The os.path.commonprefix() is a built-in Python function used to get the longest common path prefix in a list of paths. The commonprefix() method returns only the common prefix value in the specified list; returned value may or may not be a valid path as it checks for a common prefix by comparing character by character in the list.

Syntax

os.path.commonprefix(path_list)

Arguments

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

Return Value

The commonprefix() method returns a string value representing the longest common path prefix in the specified list.

Example

To use the commonprefilx() function in Python, import the os module at the head of the file first.

Then we will create a list with three elements. Each element is a path.

import os

paths = ['/Users/krunal/Desktop', 
        '/Users/krunal/Desktop/code', 
        '/Users/krunal/Desktop/datasets']

prefix = os.path.commonprefix(paths)

print("The Longest Common Path Prefix Is: ", prefix)

Output

The Longest Common Path Prefix Is:  /Users/krunal/Desktop

The list elements have one common path prefix: “/Users/krunal/Desktop“. So it returns that output.

That’s it for this tutorial.

See also

Python os.path.exists()

Python os.path.basename()

Python os.path.abspath()

Python os.path.join()

Python os.path.dirname()

Leave A Reply

Your email address will not be published.

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