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.
os.path.commonpath(list)
The function takes only one parameter:
list
: This is the set or sequence of paths defined with a specific name.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.
Let's look at the code below:
import oslist_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)
os
module.list_of_paths
.os.path.commonpath()
function and store its values in the variable mypath
.