Open In App

os.path.split() method - Python

Last Updated : 09 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

os.path.split()  method in Python is used to split a file path into two parts:

  • Head: Everything leading up to the last path component (typically the directory path).
  • Tail: The final component of the path (typically the file or folder name).

For example, consider the following path name:

path name = '/home/User/Desktop/file.txt'

For the above example:

  • Head = /home/User/Desktop/
  • Tail = file.txt

Key Behavior

  • If the path ends with a slash (/), the tail is an empty string.
  • If there is no slash in the path, the head is an empty string.
  • The returned value is always a tuple: (head, tail).

For example:

Path

Head

Tail

'/home/user/Desktop/file.txt'

'/home/user/Desktop/'

'file.txt'

'/home/user/Desktop/file.txt'

'/home/user/Desktop/'

{empty}

'file.txt'

{empty}

'file.txt'

Syntax of os.path.split() Method

os.path.split(path)

Parameter:

  • A path-like object representing a file system path. A path-like object is either a str or bytes object representing a path.

Return Type: This method returns a tuple that represents head and tail of the specified path name.

Examples os.path.split() Method

Example 1: Splitting Different File Paths

In this example, the code demonstrates the use of os.path.split() method to split a given file path into its directory (head) and file/directory name (tail). It prints the head and tail for three different path examples: '/home/User/Desktop/file.txt', '/home/User/Desktop/', and 'file.txt'.

Python
import os

path = '/home/User/Desktop/file.txt'
ht = os.path.split(path)
print("Head:", ht[0])
print("Tail:", ht[1], "\n")

path = '/home/User/Desktop/'
ht = os.path.split(path)
print("Head:", ht[0])
print("Tail:", ht[1], "\n")

path = 'file.txt'
ht = os.path.split(path)
print("Head:", ht[0])
print("Tail:", ht[1])

Output
Head: /home/User/Desktop
Tail: file.txt 

Head: /home/User/Desktop
Tail:  

Head: 
Tail: file.txt

Explanation:

  • first example separates the file from its full directory.
  • second path ends with a slash, so the tail is empty.
  • third is just a filename without any directory, so the head is empty.

Example 2: Handling an Empty Path

This example demonstrates the use of the os.path.split() method with an empty path. It shows that when an empty path is provided, the os.path.split() function returns empty strings for both the head and tail, as indicated in the comments.

Python
import os

path = ''
ht = os.path.split(path)
print("Head:", ht[0])
print("Tail:", ht[1])

Output
Head: 
Tail: 

Explanation: Providing an empty string as the path returns empty strings for both head and tail.

Related articles: os module


Next Article
Article Tags :
Practice Tags :

Similar Reads