Python os.path module’s functions can parse strings representing filenames into their component parts. It is striking to realize that these functions do not depend on the paths actually existing; they operate solely on the strings.
The os.path.split() is a built-in Python method used to split the pathname into a pair of head and tail. The tail is the last pathname component, and the head is everything leading up to that.
The os.path.split() function accepts a path-like object representing a file system path. A path-like object is either an str or bytes object representing a path.
To work with the OS module in Python, import the os module at the start of the file and use the path.split() function.
import os path = "/Users/krunal/Desktop/code/python/database/app.py" head_tail = os.path.split(path) print(head_tail)
As you can see from the output, that os.path.split() method splits the specified path into a pair called head and tail. This method generally used by os.path.dirname() and os.path.basename() method.
What if the path is empty
What if the path is empty in the path.split() function. What is the output of that? Let’s find out.
import os path = "" head_tail = os.path.split(path) print(head_tail)
As you can see from the output that it returns an empty tuple. The os.path.split() method splits a path into two parts: everything before the final slash and everything. The second element of the tuple is the last component of the path, and the first element is everything that comes before it.
That is it for the Python os.path.split() function.