Python | os.path.commonprefix () method

Python Methods and Functions

os.path.commonprefix() in Python is used to get the longest common path prefix in a list of paths. This method only returns the value of the common prefix in the specified list, the return value may or may not be a valid path as it checks for the common prefix by comparing character by character in the list. 
For example, consider the following list of paths:

  list of paths   common prefix  [`/ home / User / Photos`, / home / User / Videos`] / home / User / A valid path [`/ usr / local / bin`,` / usr / lib`] / usr / l Not a valid path 

Syntax: os.path.commonprefix (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 path prefix in specified list.

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

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

 
# import of the os module

import os

 
# List of paths

paths = [ ` / home / User / Desktop` , `/ home / User / Documents`

` / home / User / Downloads`

 
# Get
# longest common path prefix
# in the specified list

prefix = os.path.commonprefix (paths)

 

 
# Print
# longest common path prefix
# in the specified list

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

 < / code> 

 
# Path list

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

 
# Get
# longest common path prefix
# in the specified list

prefix = os.path.commonprefix (paths)

  

 
# Print
# longest common path prefix
# in the specified list

prin t ( "Longest common path prefix:" , prefix)

Exit :

 Longest common path prefix: / home / User / D Longest common path prefix: / usr / 

Note. If the specified list is empty, os.path.commonprefix ( ) will return an empty string.

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





Get Solution for free from DataCamp guru