Python provides different methods for file and directory name manipulation. The basename() method is one of the most popular methods which is used to return the basename of the specified path. The basename means the name of the specified file or directory. The file name or directory name is extracted from the complete path and the base name is returned.
Full Name = Path + Basename
Before learning and examining the basename() method of Python let’s examine what is base name and how differs it from the file or directory name. The full name consists of the path and file/directory basename. The basename specifies the name path of the complete path. In the following example “/home/ismail/” is the path and the “file.txt” is basename.
Find Basename of File
The basename() method is provided by the os module. The complete path for the basename() method is os.path.basename(). So first we import the os module in order use the basename() method.
import os.path basename = os.path.basename("/home/ismail/file.txt") print(basename)
Find Basename of Directory/Folder
A directory or folder complete path also contains a base name. The directory or folder name is the base name in the complete path. For the “/home/ismail/Downloads” the basename is “Downloads”.
import os.path basename = os.path.basename("/home/ismail/Downloads") print(basename)