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
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
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
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.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.