Python os.path.commonprefix() Method



The Python os.path.commonprefix() method is used to find the longest common prefix among a set of path strings.

  • The method compares the given paths character by character from left to right.
  • It stops comparing as soon as it encounters a character that differs among the paths or reaches the end of the shortest path.
  • The method then returns the longest common prefix found among the provided paths.
  • If no common prefix is found, it returns an empty string.

Syntax

Following is the basic syntax of the Python os.path.commonprefix() method −

os.path.commonprefix(list_of_paths)

Parameter

This method accepts a list (or any iterable) of path strings as a parameter for which you want to find the common prefix.

Return Value

The method returns a string representing the common prefix among the provided path strings.

Example

In the following example, we finding the longest common prefix among the given file paths using the commonprefix() method −

import os
paths = ["/home/lenovo/documents/file1.txt", "/home/lenovo/documents/file2.txt", "/home/lenovo/documents/file3.txt"]
prefix = os.path.commonprefix(paths)
print(prefix)    

Output

The output obtained is as follows −

/home/lenovo/documents/file

Example

Here, we are finding the longest common prefix among a mix of file paths and directory paths using the commonprefix() method −

import os
paths = ["/path/to/folder1/file.txt", "/path/to/folder2", "/path/to/folder3/file.txt"]
prefix = os.path.commonprefix(paths)
print(prefix)    

Output

Following is the output of the above code −

/path/to/folder

Example

In this example, we are finding the longest common prefix among the given URLs using the commonprefix() method −

import os
urls = ["https://example.com/path1/page1.html", "https://example.com/path2/page2.html", "https://example.com/path3/page3.html"]
prefix = os.path.commonprefix(urls)
print(prefix)       

Output

The result produced is as shown below −

https://example.com/path

Example

This example shows that if any of the paths are empty, the common prefix will also be empty −

import os
paths = ["/path/to/folder1/file.txt", "", "/path/to/folder3/file.txt"]
prefix = os.path.commonprefix(paths)
print("The longest common prefix is:",prefix) 

Output

We get the output as shown below −

The longest common prefix is: 
os_path_methods.htm
Advertisements