Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

What is os.path.basename() method in Python?

AKASH BAJWA

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Overview

OSOperating System modules provide a portable way to interact with operating system-level commands in Python. Moreover, the 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 module
import os.path
# Path
path = 'employee.csv'
basename = os.path.basename(path)
# Print the basename name
print(basename)
# ----------------------------------
# Path
path = './root/employee.csv'
basename = os.path.basename(path)
# Print the basename name
print(basename)
# ----------------------------------
# path
path = './root/usrcode/'
basename = os.path.basename(path)
# Print the basename name
print(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 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.
  • 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.

RELATED TAGS

python

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring