Python os.path.splitdrive() Method

Python os.path.splitdrive() method is used to split the drive specifier from a pathname. This method is beneficial in Windows OS, where pathnames start with a drive specifier, like “C:\” or “D:\”.

This method does not validate if the drive exists or is correct; it only parses the string based on the standard path format.

This method’s output is more relevant on Windows. On Unix and Linux OS, the drive component is always empty.

Syntax

os.path.splitdrive(path)

Parameters

Name Description
path (string) It is the path you want to split.

Return value

This method returns a 2-tuple (drive, tail) where the drive is everything before the first occurrence of a slash in the path on Windows (representing the drive letter or UNC path), and the tail is everything after that.

On systems that do not use drive specifiers (like Unix and Linux), the drive will always be an empty string.

Example 1: Windows path with drive letter

How os.path.splitdrive() method works

import os

path = "C:\\path\\to\\file.txt"
drive, tail = os.path.splitdrive(path)

print("Drive:", drive)
print("Tail:", tail)

Output

Drive: C:
Tail: \\path\to\file.txt

Example 2: Windows UNC Path

Figure of Windows UNC Path

import os

path = "\\\\server\\share\\file.txt"
drive, tail = os.path.splitdrive(path)

print("Drive:", drive)
print("Tail:", tail)

Output

Drive: \\server\share
Tail: \\file.txt

Example 3: Usage with Unix/Linux path

Usage with Unix / Linux path

import os

path = "/Users/krunallathiya/Desktop/Code/pythonenv/env/data.txt"
drive, tail = os.path.splitdrive(path)

print("Drive:", drive)
print("Tail:", tail)

Output

Drive:
Tail: /Users/krunallathiya/Desktop/Code/pythonenv/env/data.txt

We can verify that this method on Unix/Linux returns an empty drive because there is no drive in these systems.

Leave a Comment

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