Python os.path.split() Method



The Python os.path.split() method is used to split a pathname into two parts: "head" and "tail". The tail represents the last component of the pathname, which could be a file or directory name. The head contains everything leading up to that component, representing the directory part of the path.

If the specified path ends with a slash (/), the directory part will be the path itself, and the file part will be an empty string.

Syntax

Following is the basic syntax of the Python os.path.split() method −

os.path.split(path)

Parameter

This method accepts a string as a parameter representing the pathname that you want to split.

Return Value

The method returns a tuple containing the directory part and the file part of the specified path.

Example

In the following example, we are splitting the pathname "C://Users//Lenovo//Desktop//file.txt" into its directory part and filename part using the split() method −

import os
path = "C://Users//Lenovo//Desktop//file.txt"
directory, filename = os.path.split(path)
print("Directory:", directory)
print("Filename:", filename)

Output

Following is the output of the above code −

Directory: C://Users//Lenovo//Desktop
Filename: file.txt

Example

When we provide the root directory "/" as a path, the directory part will be the root directory itself, and the filename part will be empty −

import os
path = "/"
directory, filename = os.path.split(path)
print("Directory:", directory)
print("Filename:", filename) 

Output

Output of the above code is as follows −

Directory: /
Filename: 

Example

In this example, the path doesn't contain a directory part, so the directory part will be empty, and the filename part will be the entire path −

import os
path = "file.txt"
directory, filename = os.path.split(path)
print("Directory:", directory)
print("Filename:", filename) 

Output

We get the output as shown below −

Directory: 
Filename: file.txt

Example

This example shows that when the path is empty, both the directory and filename parts will be empty strings −

import os
path = ""
directory, filename = os.path.split(path)
print("Directory:", directory)
print("Filename:", filename) 

Output

The result produced is as follows −

Directory: 
Filename: 
os_path_methods.htm
Advertisements