Python os.path.split() Method

Python os.path.split() method is used to split a pathname into two parts: the directory name (head) and the base filename (tail).

Syntax

os.path.split(path)

Parameters

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

Return value

It returns a tuple that represents the head and tail of the specified path name.

The head is everything before the last slash in the path, and the tail is everything after it. This method is helpful for extracting the filename or the directory from a given path.

Example 1: Splitting a file path

Understanding of Python os.path.split() Method

import os

path = '/Users/krunallathiya/Desktop/Code/pythonenv/env/data.txt'

head, tail = os.path.split(path)
print("Head:", head)
print("Tail:", tail)

Output

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

Example 2: Splitting directory path

Splitting directory path

import os

dir_path = '/Users/krunallathiya/Desktop/Code/pythonenv/env'

head, tail = os.path.split(dir_path)
print("Head:", head)
print("Tail:", tail)

Output

Head: /Users/krunallathiya/Desktop/Code/pythonenv
Tail: env

Example 3: Filename only

Splitting only file

import os

file_path = 'data.txt'

head, tail = os.path.split(file_path)
print("Head:", head)
print("Tail:", tail)

Output

Head:
Tail: data.txt

You can see that the head is an empty string, and the tail is the file name.

Leave a Comment

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