Python | os.path.commonpath () method

Python Methods and Functions

os.path.commonpath() in Python is used to get the longest generic os. path.commonpath () in the list of paths. This method raises a ValueError if the specified list of paths either contains both absolute and relative paths, or is empty. Unlike os.path.commonpath() , the return value is a valid path. 
For example, consider the following list of paths:

  list of paths   Longest common sub-path  ['/ home / User / Photos', / home / User / Videos'] / home / User ['/ usr / local / bin',' / usr / lib'] / usr 

Syntax: os.path.commonpath (list)

Parameter:
path : A list of path-like object. A path-like object is either a string or bytes object representing a path.

Return Type: This method returns a string value which represents the longest common sub-path in the specified list.

Code # 1: Using the os.path method .commonpath ()

# Python program to explain the os.path.commonpath () method

 
# import of the os module

import os

 
# List of paths

paths = [ '/ home / User / Desktop' , ' / home / Use r / Documents'

' / home / User / Downloads'

 
# Get
# longest shared subpath
# in the specified list

prefix = os.path.commonpath ( paths)

 

 
# Print
# longest shared subpath
# in the specified list

print ( "Longest common sub -path: " , prefix)

  

  
# List of paths

paths = [ '/ usr / local / bin' , '/ usr / bin'

 
# Get
# longest shared subpath
# in the specified list

prefix = os.path.commonpath (paths)

 

 
# Print
# longest shared subpath
# in the specified list

print  ( "Longest common sub-path:" , prefix)

Exit :

 Longest common sub-path: / home / User Longest common sub-path: / usr 

Code # 2: Using the os.path.commonpath () method

# Python program for os.path.commonpath () method explanations

 
# import of the os module

import os

 
# List of paths

paths = [ ' / usr / local / bin' , 'usr / bin'  

 
# Get
# longest shared subpath
# in the specified list

prefix = os.path.commonpath (paths)

 

 
# Print
# longest shared subpath
# in the specified list

print ( "Longest common sub-path:" , prefix)

 

 
# The above code will boost
# ValueErro r as a list of paths
# contains both absolute and
# relative path

Exit:

 Traceback (most recent call last) : File "oscommonpath.py", line 12, in prefix = os.path.commonpath (paths) File "/usr/lib/python3.6/posixpath.py", line 505, in commonpath raise ValueError ("Can't mix absolute and relative paths ") from None ValueError: Can't mix absolute and relative paths 

Note. If the specified list is empty os .path.commonpath () will also raise ValueError .

Link: https://docs.python.org/3/library/os.path.html



Tutorials