The os
module in the standard library includes the os.path
submodule which provides a number of tools for working with and manipulating paths.
The basename()
function in the module is used to get the base name of a specified path. It is typically used to extract the file/directory name from a path, since it returns only the file name excluding the directory path.
We have to import the function from the module before using it in our program as shown below
from os.path import basename
basename(path)
path |
The path from which the base name is to be extracted. |
#on a Unix system
from os.path import basename
path = '/usr/local/bin/python'
name = basename(path)
print(name)
In the above example, we have a path to a directory called 'python'. Passing the path to the basename()
function we get the name of the directory without the directory path.
The following example uses a file path rather than a directory path as the argument.
#on a Windows system
from os.path import basename
path = r"C:\users\John\desktop\myfile.txt"
name = basename(path)
print(name)
myfile.txt
In the above example we have a file named "myfile.txt" in the users desktop directory, the basename()
function returns the file name without path details.
Note that the function does not perform any validation to check whether the input string represents a valid path or not. It works on mere strings.