A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-os-path-split-method/ below:

os.path.split() method - Python - GeeksforGeeks

os.path.split() method - Python

Last Updated : 11 Jul, 2025

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

For example, consider the following path name:

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

For the above example:

Key Behavior

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:

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:

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])

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

Related articles: os module



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4