Python os.path.splitdrive() Method



The Python os.path.splitdrive() method is used to split a pathname into two parts: "drive" and "tail". On Windows systems, drive represents the drive letter part of the pathname, while tail denotes the remainder. On Unix-like systems, drive is an empty string.

This method is primarily useful in Windows environments where paths often start with a drive letter followed by a colon (:).

A drive letter is a single alphabetic character, followed by a colon (:), used to identify storage devices like hard drives and partitions in Windows systems.

Syntax

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

os.path.splitdrive(path)

Parameter

This method accepts a string as a parameter representing the pathname that you want to split.

Return Value

The method returns a tuple containing the drive part and the rest of the path. If the specified path does not have a drive part, the drive part will be an empty string.

Example

In the following example, we are splitting the Windows path "C://Users//Lenovo//Desktop//file.txt" into its drive part and the rest of the path using the splitdrive() method −

import os
path = "C://Users//Lenovo//Desktop//file.txt"
drive, rest = os.path.splitdrive(path)
print("Drive:", drive)
print("Rest:", rest)

Output

Following is the output of the above code −

Drive: C:
Rest: //Users//Lenovo//Desktop//file.txt

Example

When we provide only a drive letter as a path, the drive part will be the drive letter itself, and the rest will be an empty string −

import os
path = "C:"
drive, rest = os.path.splitdrive(path)
print("Drive:", drive)
print("Rest:", rest)

Output

Output of the above code is as follows −

Drive: C:
Rest:  

Example

Relative paths do not have a drive part, so the drive part will be empty, and the entire path will be considered as the rest of the path −

import os
path = "home/lenovo/documents/file.txt"
drive, rest = os.path.splitdrive(path)
print("Drive:", drive)
print("Rest:", rest)

Output

We get the output as shown below −

Drive: 
Rest: home/lenovo/documents/file.txt

Example

This example shows that when the path is empty, both the drive and rest parts will be empty strings −

import os
path = ""
drive, rest = os.path.splitdrive(path)
print("Drive:", drive)
print("Rest:", rest)

Output

The result produced is as follows −

Drive: 
Rest:
os_path_methods.htm
Advertisements