The os
module in the standard library includes the path
submodule which offers convenient functions for working with and manipulating paths.
The split()
function in the path
submodule is used to split a string representing a pathname into its individual components i.e the directory and the name.
To use the function, we have to first import it in our program as shown below.
from os.path import split
split(p)
p |
The path to be split. |
The function returns a two-length tuple where the first elements is everything before the last slash(the directory path) and the second element is everything after the last slash(the path name). The function does not perform any validation to check whether the input string represents a valid path or not, it works on mere strings.
#on windows
from os.path import split
p = r"C:\users\John\desktop\myfile.txt"
dir, name = split(p)
print(dir)
print(name)
C:\users\John\desktop
myfile.txt
In the above example, we passed the path to the split()
function, we then unpacked the returned tuple into variables dir
and name
.
Note that the function uses the os.sep character as the path delimiter, thus on Unix systems, a forward slash will be used rather than a backward slash.
The returned tuple may contain an empty string, for example if the input path ends with a slash, the second part of the returned tuple will be an empty string while if the input string has no slash, the first part of the returned tuple will be an empty string.