Python os.path.commonprefix() Method

The os.path.commonprefix() method in Python is used to find the longest common prefix string amongst a list of strings.

Syntax

os.path.commonprefix(path_list)

Parameters

Name Description
list (list of strings)  A list of pathnames.

Return Value

It returns a string representing the longest common prefix (taken character by character) that is a prefix of all paths in the list.

Example 1: Finding common prefixes of paths

import os

paths = ['/home/user/docs/data.txt',
         '/home/user/docs/file.txt',
         '/home/user/document']

common_prefix = os.path.commonprefix(paths)

print("Common prefix:", common_prefix)

Output

Common prefix: /home/user/doc

Example 2: Finding a common prefix within a list of strings

import os

strings = ['abcdef', 'abcxyz', 'abc123']

common_prefix = os.path.commonprefix(strings)

print("Common prefix:", common_prefix)

Output

Common prefix: abc

While os.path.commonprefix() can help find the longest common substring in a list of strings, caution is needed for path manipulations.

For finding the common path of a list of file paths, os.path.commonpath() is usually more appropriate, as it understands the filesystem path semantics.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.