What is os.path.basename() method in Python?
Overview
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.
Syntax
os.path.basename(path)
Parameters
It takes only a single argument value:
path: This is a string or path-like object representing a file path in a local system.
Return value
It returns the tail part of the path as a string value.
Code
# 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)
Explanation
In this code, we'll elaborate on the os.path.basename() function and how we can use it in our program.
- Lines 4–7: We'll use the
pathvariable. It already contains the base name of a pathname. Thus, we'll use thepath.basename(path)function to return the file name'employee.csv'as it is. - Lines 10–13: We've a path that contains the pathname of the file. We'll use the
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. - Lines 16–19: In this case, the
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.