os.path
allows handling files in different places of a local file system.
We use the os.path.basename()
function to extract a specified path name's base name. It invokes os.path.split()
to split the whole file path into a pair of head and tail paths. Therefore, it returns the tail part only.
os.path.basename(path)
It takes only a single argument value:
path
: This is a string or path-like object representing a file path in a local system.It returns the tail part of the path as a string value.
# importing os.path moduleimport os.path# Pathpath = 'employee.csv'basename = os.path.basename(path)# Print the basename nameprint(basename)# ----------------------------------# Pathpath = './root/employee.csv'basename = os.path.basename(path)# Print the basename nameprint(basename)# ----------------------------------# pathpath = './root/usrcode/'basename = os.path.basename(path)# Print the basename nameprint(basename)
In this code, we'll elaborate on the os.path.basename()
function and how we can use it in our program.
path
variable. It already contains the base name of a pathname. Thus, we'll use the path.basename(path)
function to return the file name 'employee.csv'
as it is. path.basename(path)
to return the base file name (employee.csv
) only. Because it splits a pathname into head and tail parts. Thus, file name is returned and printed on the console.path='./root/usrcode/'
does not contain the base file name. Thus, the head part will be ./root/usrcode/
while the tail will be empty (' ')
. So, it will print whitespace on the console.