What is the os.path.commonpath() method in Python?

Overview

Python allows its users to communicate with the operating systems through the os module. This module exists as a bridge or communication system with various built-in functions that allow interacting with the operating system.

Out of various functions, we'll discuss the os.path.commonpath() method. This method is used to interact with the paths of the system, and it returns the longest common path from the given list.

Note: This function can only be used with Unix and Windows operating systems.

Syntax


os.path.commonpath(list)

Parameter

The function takes only one parameter:

  • list: This is the set or sequence of paths defined with a specific name.

Return value

This function will return the longest common path from the given sequence.

Note: This function will generate a value error if:
 1. The paths mentioned in the list have both absolute and relative paths.
2. The list passed to the function is empty.

Code

Let's look at the code below:

import os
list_of_paths = ['/Users/Hp-Elite-Book/Desktop',
'/Users/Hp-Elite-Book/Desktop/mypythoncode',
'/Users/Hp-Elite-Book/Desktop/mysql']
mypath = os.path.commonpath(list_of_paths)
print("The Longest Common Sub-Path is: ", mypath)

Explanation

  • Line 1: We import the os module.
  • Line 2: We define the paths inside an array named as list_of_paths.
  • Line 5: We call the os.path.commonpath() function and store its values in the variable mypath.
  • Line 6: We display the string that is returned by the function and is stored in the previous line.

Free Resources